Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Pessoal, tenho uma dúvida aqui em relação ao PDO::FETCH_ASSOC... Essa função deve selecionar todos os valores existentes em "user_key" e depois criar uma que seja diferente.
Ai incluir um diretório com key de usuário...
Fui executar um teste e apareceu na tela o seguinte erro:
Fatal error: Call to undefined method PDO::fetch_assoc() in /home/project/public_html/desenvolvimento/class/Register.class.php on line 31
private function getKeys(){
$select = self::getConnection()->prepare('SELECT `user_key` FROM `'. $this->_table .'`');
$select->execute();
while($f = PDO::FETCH_ASSOC($select)){
$keys[]= $f['user_key'];
}
$key = rand(10000000000,99999999999);
while(in_array($key,$keys)){
$key= rand(1111111111,9999999999);
}
$new_dir = "user/$key";
if(mkdir($new_dir)){
mkdir($new_dir."/images");
mkdir($new_dir."/documents");
mkdir($new_dir."/songs");
mkdir($new_dir."/videos");
}
}
Agradeço qualquer ajuda.
Obrigado
heheheh vou te confessar que eu também tentei inventar..
Vou fazer as alterações aqui e já retorno!!
Obrigadão!
Pois é, agora ele imprime um erro de array nos valores que são passados na hora de fazer o insert...
Vou colocar a classe toda aqui para que possa dar uma olhada...
<?
class Register extends Connection {
public $error;
private $data;
private $_table;
function __construct(array $data, $table='usuarios') {
$this->_table = $table;
$this->data = $data;
$this->reg();
}
private function encrypt($senha) {
return hash('whirlpool', $senha);
}
private function check($email) {
$check = self::getConnection()->prepare('SELECT `id_usuario` FROM `' . $this->_table . '` WHERE `email`= ? LIMIT 1');
$check->execute(array($email));
return $check->rowCount() == 0 ? true : false;
}
private function getKeys(){
$select = self::getConnection()->prepare('SELECT `user_key` FROM `'. $this->_table .'`');
$select->execute();
$key = $select->fetchAll(PDO::FETCH_ASSOC);
foreach($key as $keys){
$keys[] = $f['user_key'];
}
$new_dir = "user/$key";
if(mkdir($new_dir)){
mkdir($new_dir."/images");
mkdir($new_dir."/documents");
mkdir($new_dir."/songs");
mkdir($new_dir."/videos");
}
}
private function validate() {
foreach ($this->data as $colunm => $value) {
if ($colunm == 'senha') {
$this->data[$colunm] = $this->encrypt($value);
}
if ($value == '') {
$this->error = 'O campo <strong>' . $colunm . '</strong> é obrigatório!';
}
}
if ($colunm == 'email' AND !preg_match("/^[a-z0-9_\.\-]+@[a-z0-9_\.\-]*[a-z0-9_\-]+\.[a-z]{2,4}$/i", $value)) {
$this->error = 'O email digitado não é válido!';
}
if (strtolower($this->data['captcha']) <> strtolower($_SESSION['captcha'])) {
$this->error = 'O captcha não confere com a imagem!';
}
}
private function setData() {
return '`' . implode('`= ?, `', array_keys($this->data)) . '`= ?';
}
private function reg() {
$this->validate();
if ($this->check($this->data['email'])) {
if (empty($this->error)) {
unset($this->data['captcha']);
$this->getKeys();
$insert = self::getConnection()->prepare('INSERT INTO ' . $this->_table . ' SET ' . $this->setData() . ', `dt_cadastro`= NOW(), `key_val` = '. $key .'');
if ($insert->execute(array_values($this->data))) {
echo "<script>document.location = 'login.php'</script>";
exit();
} else {
$this->error = 'Não foi possivel fazer seus cadastro, tente novamente mais tarde!';
}
}
} else {
$this->error = 'O e-mail digitado já está cadastrado.';
}
}
function getErrors() {
return $this->error;
}
}
?>
Tem alguma
Ops, não saiu o final..
Continuando
... Tem alguma solução, alguma forma que esse valor não entre nesse array ou então entre de forma correta?
obrigado
dando uma olhada rapida você declara $key no insert mais ele vem de onde?
ta dentro de uma class então seria assim.. pelo q podi ve no seu codigo
notei q você ta usando o INSERT como UPDATE ????
UPDATE = "UPDATE `$this->_table` SET
nomeNoticia=:nome, tagsNoticia=:tags, textNoticia=:text, thumbImg=:img,
idLigaCategoria=:idCateg, statusItem=:status
WHERE $this->campo=:id";
INSERT = "INSERT INTO `$this->_table`
( nomeNoticia, tagsNoticia, textNoticia, thumbImg, idLigaCategoria, statusItem )
VALUES
( :nome, :tags, :text, :img, :idCateg, :status )";
assim q aprendi =X
private function getKeys(){
$select = self::getConnection()->prepare('SELECT `user_key` FROM `'. $this->_table .'`');
$select->execute();
$key = $select->fetchAll(PDO::FETCH_ASSOC);
foreach($key as $keys){
$keys[] = $f['user_key'];
}
$new_dir = "user/$key";
if(mkdir($new_dir)){
mkdir($new_dir."/images");
mkdir($new_dir."/documents");
mkdir($new_dir."/songs");
mkdir($new_dir."/videos");
}
return $key; ///Aqui eu retorno a $key com os arrays;
}
//logo adiante
$key = $this->getKeys();
$insert = self::getConnection()->prepare('INSERT INTO ' . $this->_table . ' SET ' . $this->setData() . ', `dt_cadastro`= NOW(), `key_val` = '. $key .''); // agora a variavel key passa a ter um valor
//ou
private $key=null;
private function getKeys(){
return $this->key;
}
private function reg(){
INSERT INTO tabela (key)values('$this->key')
}Pois é, eu fiz todas as alterações certinhas..
O erro agora ta assim:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'field list'' in /home/nightins/public_html/desenvolvimento/class/Register.class.php:86 Stack trace: #0 /home/nightins/public_html/desenvolvimento/class/Register.class.php(86): PDOStatement->execute(Array) #1 /home/nightins/public_html/desenvolvimento/class/Register.class.php(14): Register->reg() #2 /home/nightins/public_html/desenvolvimento/cadastro.php(30): Register->__construct(Array) #3 {main} thrown in /home/nightins/public_html/desenvolvimento/class/Register.class.php on line 86
e a classe assim:
<?
class Register extends Connection {
public $error;
private $data;
private $_table;
function __construct(array $data, $table='usuarios') {
$this->_table = $table;
$this->data = $data;
$this->reg();
}
private function encrypt($senha) {
return hash('whirlpool', $senha);
}
private function check($email) {
$check = self::getConnection()->prepare('SELECT `id_usuario` FROM `' . $this->_table . '` WHERE `email`= ? LIMIT 1');
$check->execute(array($email));
return $check->rowCount() == 0 ? true : false;
}
private function getKeys() {
$select = self::getConnection()->prepare('SELECT `user_key` FROM `' . $this->_table . '`');
$select->execute();
$key = $select->fetchAll(PDO::FETCH_ASSOC);
foreach ($key as $keys) {
$keys[] = $f['user_key'];
}
$new_dir = "user/$key";
if (mkdir($new_dir)) {
mkdir($new_dir . "/images");
mkdir($new_dir . "/documents");
mkdir($new_dir . "/songs");
mkdir($new_dir . "/videos");
}
return $key;
}
private function validate() {
foreach ($this->data as $colunm => $value) {
if ($colunm == 'senha') {
$this->data[$colunm] = $this->encrypt($value);
}
if ($value == '') {
$this->error = 'O campo <strong>' . $colunm . '</strong> é obrigatório!';
}
}
if ($colunm == 'email' AND !preg_match("/^[a-z0-9_\.\-]+@[a-z0-9_\.\-]*[a-z0-9_\-]+\.[a-z]{2,4}$/i", $value)) {
$this->error = 'O email digitado não é válido!';
}
if (strtolower($this->data['captcha']) <> strtolower($_SESSION['captcha'])) {
$this->error = 'O captcha não confere com a imagem!';
}
}
private function setData() {
return '`' . implode('`= ?, `', array_keys($this->data)) . '`= ?';
}
private function reg() {
$this->validate();
if ($this->check($this->data['email'])) {
if (empty($this->error)) {
unset($this->data['captcha']);
$key = $this->getKeys();
$insert = self::getConnection()->prepare('INSERT INTO ' . $this->_table . ' SET ' . $this->setData() . ', `dt_cadastro`= NOW(), `user_key` = ' . $key . '');
if ($insert->execute(array_values($this->data))) {
echo "<script>document.location = 'login.php'</script>";
exit();
} else {
$this->error = 'Não foi possivel fazer seus cadastro, tente novamente mais tarde!';
}
}
} else {
$this->error = 'O e-mail digitado já está cadastrado.';
}
}
function getErrors() {
return $this->error;
}
}
?>
Em relação ao insert, ele funcionava bem.. O unico problema agora é que eu estou tentando criar os diretórios junto com o cadastro do usuário.
seu erro e de SQL a coluna não foi encontrada linha 86..
Esse seu INSERT ja funciono alguma vez?
qual seria a linha 86?
private function setData() {
// dessa forma você tem q usa bindValue no seu PDO
return '`' . implode('`= ?, `', array_keys($this->data)) . '`= ?';
}
$insert = self::getConnection()->prepare('INSERT INTO ' . $this->_table . ' SET ' . $this->setData() . ', `dt_cadastro`= NOW(), `user_key` = ' . $key . '');
if ($insert->execute(array_values($this->data))) {// essa linha ta errada
echo "<script>document.location = 'login.php'</script>";
a dica q te do muda essa sua forma de insert ela ta estranha..
da um var_dump em $this->data .. oq ta printando isso?
Então, o insert ele funciona tranquilo.. Antes de eu colocar a função de criação de diretório ele funcionava bem..
Aqui o resultado com o array dos valores:
array(6) { ["nome"]=> string(6) "Renato" ["sobrenome"]=> string(19) "Rodrigues de Araujo" ["email"]=> string(25) "renato.r.araujo@gmail.com" ["senha"]=> string(128) "ed54790c602909db940b42ddb260f37cf8b0dfebd730c0a6f136a733aba4de943b002a7bf90b66b9d4dcd9e0ae54b8ddfb6cddd32d59e58192397ec4a34ec29e" ["dt_nascimento"]=> string(10) "1992-01-20" ["sexo"]=> string(9) "Masculino" }
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'field list'' in /home/nightins/public_html/desenvolvimento/class/Register.class.php:89 Stack trace: #0 /home/nightins/public_html/desenvolvimento/class/Register.class.php(89): PDOStatement->execute(Array) #1 /home/nightins/public_html/desenvolvimento/class/Register.class.php(14): Register->reg() #2 /home/nightins/public_html/desenvolvimento/cadastro.php(30): Register->__construct(Array) #3 {main} thrown in /home/nightins/public_html/desenvolvimento/class/Register.class.php on line 89
A função onde ele está encontrando o erro com a linha 86 logo abaixo do comentário "linha 86":
private function reg() {
$this->validate();
if ($this->check($this->data['email'])) {
if (empty($this->error)) {
unset($this->data['captcha']);
$key = $this->getKeys();
var_dump($this->data);
$insert = self::getConnection()->prepare('INSERT INTO ' . $this->_table . ' SET ' . $this->setData() . ', `dt_cadastro`= NOW(), `user_key` = ' . $key . '');
// linha 86
if ($insert->execute(array_values($this->data))) {
echo "<script>document.location = 'login.php'</script>";
exit();
} else {
$this->error = 'Não foi possivel fazer seus cadastro, tente novamente mais tarde!';
}
}
} else {
$this->error = 'O e-mail digitado já está cadastrado.';
}
}$this->setData(); ele ta montando a string certinha pra SQL?
printa ela e ve oque ta rolando.. seu problema e esse INSERT ai misturado com UPDATE =D
qnto ao diretorio ..
function makeDir($key){
mkdir($key."/images");
mkdir($key."/documents");
mkdir($key."/songs");
mkdir($key."/videos");
}
$key = $this->getKeys();
$this->makeDir($key);
$insert = self::getConnection()->prepare('INSERT INTO ' . $this->_table . ' SET ' . $this->setData() . ', `dt_cadastro`= NOW(), `user_key` = ' . $key . '');
if ($insert->execute(array_values($this->data))) {
echo "<script>document.location = 'login.php'</script>";
exit();
rapa te confesso q e a primeira vez q vejo o fetch se usado assim no while =X
geralmente e assim