If i don't change at least 1 of the fields values, the update fails.
Insert works ok.
My git
https://github.com/emerson-cs-santos/TSI-PI_2-2019/blob/master/PHP/novo_user.php
If i keep doing this:
$status = $status . ' ';
works, but it's sound me the right solution
-- MYSQL --
CREATE DATABASE IF NOT EXISTS SENAC_PI;
USE SENAC_PI;
CREATE TABLE IF NOT EXISTS USUARIOS
(
codigo INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY
,nome VARCHAR(20) NOT NULL
,senha VARCHAR(200) NOT NULL
,tipo VARCHAR(20) NOT NULL
)
;
-- PHP --
<?php
// Open a Connection to MySQL
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "SENAC_PI";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
echo 'errado';
return;
}
$query = 'use SENAC_PI';
$result = $conn->query($query);
$codigo = 0;
$login = 'teste';
$senha = '123';
$status = 'Ativo';
$query =
" INSERT INTO USUARIOS ( codigo, nome, senha, tipo ) Values (?, ?, ?, ?)";
$querytratada = $conn->prepare($query);
$querytratada->bind_param("isss",$codigo,$login,$senha,$status);
$querytratada->execute();
if ($querytratada->affected_rows > 0)
{
$resposta = 'ok';
}
else
{
$resposta = 'erro';
}
-- update
$query =
" UPDATE USUARIOS SET nome = ? ,senha = ? , tipo = ? where codigo = ? ";
$querytratada = $conn->prepare($query);
$querytratada->bind_param("sssi",$login,$senha,$status,$codigo);
$querytratada->execute();
if ($querytratada->affected_rows > 0)
{
$resposta = 'ok';
}
else
{
$resposta = 'erro';
}
}
?>
If i don't change at least 1 of the fields values, then query returns: affected_rows = 0
Thanks to Nigel, i managed to verif the result.
I was using "affected_rows" to valid for errors, but if the user doesn't change something, my code will return as an error.
Using "Rows matched" and "Warnings", i can make sure that my query doesn't have errors.
My final code for the problem:
preg_match_all ('/(\S[^:]+): (\d+)/', $conn->info, $querytratada);
$info = array_combine ($querytratada[1], $querytratada[2]);
// Linhas encontradas com base na condição da where
$linhas_encontradas = $info['Rows matched'];
// Linhas que foram alteradas, quando os dados não forem alterados, mesmo o comando estando certo, não é retornado linhas afetadas
$linhas_afetadas = $info['Changed'];
// Avisos de problemas
$avisos_problemas = $info['Warnings'];
//if ($querytratada->affected_rows > 0)
if ($linhas_encontradas == '1' and $avisos_problemas == '0')
{
$resposta = 'ok';
}
else
{
$resposta = 'erro';
}
Anyway, thanks again Nigel!
Related
I'm trying to UPDATE multiple rows of my DB, but it UPDATE only the last row.
I got all DATA from database and fill the SELECT OPTION MULTIPLE:
<select name="numerosdasorte[]" class="form-control" multiple="">
<?php
$consulta = $PDO->query("SELECT * FROM cota1 WHERE status = '0' ORDER BY cota ASC");
while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
?>
<option value="<?php echo $linha['cota']; ?>"><?php echo $linha['cota']; ?></option>
<?php } ?>
</select>
I got these numbers and I put ',' before save data:
$numerosdasorte = '';
foreach ($_POST['numerosdasorte'] as $numeros) {
$numerosdasorte .= ',' . $numeros;
}
$numerosdasorte = ltrim($numerosdasorte, ',');
I INSERT the data on DATABASE. It works like I want:
$sql = "INSERT INTO users SET name = :name, email = :email, password = :password, endereco = :endereco, numero = :numero, bairro = :bairro, cep = :cep, cidade = :cidade, estado = :estado, telefonefixo = :telefonefixo, telefonecelular = :telefonecelular, datadenascimento = :datadenascimento, cpfcnpj = :cpfcnpj, rg = :rg, numerosdasorte = :numerosdasorte";
Now, I got the problem: I need to get the number that was picked in the form to change this status. All the numbers picked, I need to change to '1'. All the numbers picked needs to be unavailable:
$exploded = explode(",", $numerosdasorte);
foreach( $exploded as $key => $value ) {
$query = "UPDATE cota1 SET status = '1' WHERE cota = $value";
$stmt = $PDO->prepare($query);
}
The problem is, the only row affected is the last. If I choice 5 numbers, for example (001, 002, 003, 004 and 005), only the last number (005) will be affected and changed to '1'.
COMPLETE CODE:
<?php
require '../config.a/conexao.php';
$name = $_POST['name'];
$email = $_POST['email'];
$password = md5(uniqid(""));
$endereco = $_POST['endereco'];
$numero = $_POST['numero'];
$bairro = $_POST['bairro'];
$cep = $_POST['cep'];
$cidade = $_POST['cidade'];
$estado = $_POST['estado'];
$telefonefixo = $_POST['telefonefixo'];
$telefonecelular = $_POST['telefonecelular'];
$datadenascimento = $_POST['datadenascimento'];
$cpfcnpj = $_POST['cpfcnpj'];
$rg = $_POST['rg'];
$numerosdasorte = '';
foreach ($_POST['numerosdasorte'] as $numeros) {
$numerosdasorte .= ',' . $numeros;
}
$numerosdasorte = ltrim($numerosdasorte, ',');
$sql = "INSERT INTO users SET name = :name, email = :email, password = :password, endereco = :endereco, numero = :numero, bairro = :bairro, cep = :cep, cidade = :cidade, estado = :estado, telefonefixo = :telefonefixo, telefonecelular = :telefonecelular, datadenascimento = :datadenascimento, cpfcnpj = :cpfcnpj, rg = :rg, numerosdasorte = :numerosdasorte";
$stmt = $PDO->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':endereco', $endereco);
$stmt->bindParam(':numero', $numero);
$stmt->bindParam(':bairro', $bairro);
$stmt->bindParam(':cep', $cep);
$stmt->bindParam(':cidade', $cidade);
$stmt->bindParam(':estado', $estado);
$stmt->bindParam(':telefonefixo', $telefonefixo);
$stmt->bindParam(':telefonecelular', $telefonecelular);
$stmt->bindParam(':datadenascimento', $datadenascimento);
$stmt->bindParam(':cpfcnpj', $cpfcnpj);
$stmt->bindParam(':rg', $rg);
$stmt->bindParam(':numerosdasorte', $numerosdasorte);
$exploded = explode(",", $numerosdasorte);
foreach( $exploded as $key => $value ) {
$query = "UPDATE cota1 SET status = '1' WHERE cota = $value";
$stmt = $PDO->prepare($query);
}
$result = $stmt->execute();
if (!$result) {
var_dump($stmt->errorInfo());
} else {
$subjectPrefix = '[Você foi cadastrado na TOP BRASIL]';
$assunto = 'Você foi cadastrado na TOP BRASIL';
$mensagemHTML = '<h3>Parabéns por fazer parte do nosso GRUPO COOPERATIVO!</h3>
<p>Olá <b>' . $name . '</b>, você fez uma ótima escolha! Acompanhe os sorteios e boa sorte! <br> Agora você está habilitado a acompanhar todo o processo por seu PAINEL de cliente. Para acessar, é muito simples: <br> Acesse nosso site (https://topbrasilbr.com.br/painel), digite seu usuário e senha, e pronto! Fique por dentro das novidades! <br><br> Segue seus dados de cadastro:
<p><b>E-mail:</b> ' . $email . ' <br> <b>Senha:</b> ' . $password . '
<p>Para dúvidas, entre em contato conosco, pelo telefone (24) 2252-3196, ou pelo e-mail: contato#topbrasilbr.com.br.
<p>Um grande abraço!
<p><b>Equipe TOP BRASIL</b>
<hr>';
$headers = "MIME-Version: 1.1\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: TOP BRASIL\r\n";
$headers .= 'Cc: contato#topbrasilbr.com.br' . "\r\n";
$headers .= "Return-Path: $email \r\n";
$envio = mail($email, $assunto, $mensagemHTML, $headers);
if ($envio)
echo "<script>alert('Cadastro realizado com sucesso!'); window.top.location.href = 'index.php';</script>";
}
exit;
?>
For your first insert query, you never execute it. No records are being created. For the second, you're preparing a statement over and over again with different values, but you only execute once at the end of it all. One of the primary reasons for using a prepared statement is so that you DO NOT put the user data directly into the SQL, as you are doing.
In addition to all that, your whole script can be shortened considerably.
<?php
require '../config.a/conexao.php';
// I don't know what you're doing here, but it's not good
$_POST["password"] = md5(uniqid(""));
// here just turn post into your parameters by prefixing key with :
foreach ($_POST as $k=>$v) {
$params[":$k"] = $v;
}
// this is a special case, but the fact that it's here means
// your database structure is no good and needs normalizing
$params[":numerosdasorte"] = implode($_POST["numerosdasorte"], ',');
// prepare the statement
$stmt = $PDO->prepare(
"INSERT INTO users SET name = :name, email = :email, password = :password, endereco = :endereco, numero = :numero, bairro = :bairro, cep = :cep, cidade = :cidade, estado = :estado, telefonefixo = :telefonefixo, telefonecelular = :telefonecelular, datadenascimento = :datadenascimento, cpfcnpj = :cpfcnpj, rg = :rg, numerosdasorte = :numerosdasorte"
);
// no need to bind parameters, just include them as an array in the execution
$result = $stmt->execute($params);
// again, prepare a statement
$stmt = $PDO->prepare("UPDATE cota1 SET status = 1 WHERE cota = ?");
foreach($_POST["numerosdasorte"] as $value ) {
// execute it repeatedly
$stmt->execute([$value]);
}
if (!$result) {
// don't show users this stuff
var_dump($stmt->errorInfo());
} else {
// send your email
}
Try where ... in query for the update. I am assuming that $exploded has an array of numbers like [121, 122, 123];
$exploded = explode(",", $numerosdasorte); // holds only numbers in the array
Then you can do something like this:
$query = "UPDATE cota1 SET status = '1' WHERE cota in ($exploded)"; // it is similar to fire query like "UPDATE cota1 SET status = '1' WHERE cota in (121, 122, 123)"
$stmt = $PDO->prepare($query);
In that case, you don't need the foreach loop as you are passing an array directly for update.
Just a quick reference to help you https://www.w3resource.com/mysql/comparision-functions-and-operators/in-function.php
I would appreciate it if someone can guide me with the following problem, I need to do a INSERT into a MySQL database with variables, here is my code example:
$valor = "$valor.", ".$total;
$table = $dta.$year;
$insert = "ano, id, idas".$valor2.", total";
$value = $year.", ".$id.", ".$idas.$tit2.", ".$monto3;
$sql = "INSERT INTO `$table` (`$insert`) VALUES (`$value`)";
The general idea is that the amount of columns are not known until the program is run as it is all dynamic.
The following code is used to build the table as needed, which works fine:
while(($row = mysql_fetch_array($result)) !== FALSE)
{
$columna=$row['pn'];
$valor= $valor." pt".$columna." VARCHAR(50),";
$valor2= $valor2.", pt".$columna;
$gestion = '3';
$table = "sumag".$gestion.$year;
}
$valor= "ano VARCHAR(4), id VARCHAR(4), idas VARCHAR(13), ".$valor." "."total VARCHAR(10)";
For this reason the first code also has to be dynamic..
I really need help on this, I am not a programmer and I have built this from what I have learnt, so most probally my tecnique is pretty bad, if anyone can help it would be great..
Thank You
You have declared the column name as idas VARCHAR(13), in table but the insert element declared with some additional values idas".$valor2.". Check this one instance right now..
Here is the full code:
<?php
$gestion = 3;
$data = "SELECT * FROM progdesc where gestion = '$gestion'" or die("¡Error No existe ese departamento!");
$result = mysql_query($data) or die("¡Error No existe ese dep!");
while(($row = mysql_fetch_array($result)) !== FALSE)
{
$columna=$row['pn'];
$valor= $valor." pt".$columna." VARCHAR(50),";
$valor2= $valor2.", pt".$columna;
$gestion = '3';
$table = "sumag".$gestion.$year;
}
$valor= "ano VARCHAR(4), id VARCHAR(4), idas VARCHAR(13), ".$valor." "."total VARCHAR(10)";
#echo $table." - ".$valor;
mysql_query("CREATE TABLE `".$table."`(".$valor.")") or die(mysql_error());
//------------------------------------Insert data -----------------------------------------//
//-1--------Get Asig N°--------//
$data1 = "SELECT * FROM asigna" or die("¡Error No existe ese departamento!");
$result1 = mysql_query($data1) or die("¡Error1!");
while(($row = mysql_fetch_array($result1)) !== FALSE)
{
$id=$row['id'];
$idas=$row['idas'];
$sid=$row['sid'];
$tit2 = NULL;
$monto3 = 0;
//-2-------Get Gestion and DEPFINAL---------------------//
$data2 = "SELECT * FROM progdesc WHERE gestion = '$gestion' and ano = '$year' " or die("¡Error No existe ese departamento!");
$result2 = mysql_query($data2) or die("¡Error2!");
while(($row2 = mysql_fetch_array($result2)) !== FALSE)
{
$dep=$row2['departamento'];
$titulo=$row2['titulo'];
$depf = $dep."final";
$pn = $row2['pn'];
$sidb = $row2['sid'];
#$monto3 = 0;
#echo $pn;
//-3-------Get Program N° and create chain------------//
$data3 = "SELECT * FROM $depf WHERE ano = '$year' and idas = '$idas' and gestion = '$gestion'and programa = '$pn' " or die("¡Error No existe ese departamento!");
$result3 = mysql_query($data3) or die("¡Error3!");
while(($row3 = mysql_fetch_array($result3)) !== FALSE)
{
$monto=$row3['monto'];
if (!($idas2 == $idas and $monto == 0)){
$tit2 = $tit2.", ".$monto;
}elseif ($monto == 0){
$tit2 = $tit2.", 0";
} else {
$cero = 0;
$pn2 = 0;
If (!($monto == 0)){
for ($i = 0; $i < $pn2; $i++) {
$cero = $cero.", 0";
}
$tit2 = $tit2.", ".$cero.", ".$monto;
}
}
$idas2 = $idas;
$ln = $ln + 1;
$monto2 = $monto;
$monto3 = $monto3 + $monto;
}
}
$insert = "ano, id, idas".$valor2.", total";
$value = $year.", ".$id.", ".$idas.$tit2.", ".$monto3;
$sql = "INSERT INTO `$table` (`$insert`) VALUES (`$value`)";
myquery($sql); }
I just want to make clear that I am not a programmer and I know my code is not up to standard in any way, I was forced to complete this task just because I kinda know programming, this is why I am asking for help, if there is anther way to complete the task, great and thanks fr all have responded so far, I apreciate your patience.
The problem I'm having is making preg_match work correctly for my array returned from my form.
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 1 (123)">
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 2 (456)">
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 3 (789)">
So I wish to use preg_match on the values received through my form.
This is how I use it.
$msg_receivers = !empty($_POST['receiver-check']) && is_array($_POST['receiver-check']) ? $_POST['receiver-check'] : array();
$receiverIds = array();
foreach($msg_receivers as $receiver) {
$receiverIds[] = preg_replace('/\((\d+)\)$/', "$1", $receiver);
}
$number_of_receivers = count($receiverIds);
$while_count = 0;
while($number_of_receivers >= ($while_count + 1)){
$sql = <<< EOF
INSERT INTO private_messages (
message_subject,
message_content,
message_deliver,
message_receive,
message_status,
message_datetime,
message_to_stab
)VALUES
(?,?,?,?,'2',?,?);
EOF;
$stmt = $mysqli->prepare($sql) or die ("Feil i database<br>" . $sql . "<br><b>Feilmelding:</b> " . $mysqli->error);
$stmt->bind_param("ssiiii",$message_subject,$message_content, $_SESSION['user_id'],$receiverIds[$while_count],$message_datetime,$message_to_stab);
$stmt->execute() or die("noe gikk galt");
$msg_num_rows = $stmt->num_rows;
if($msg_num_rows = 0){
$msg = "Feilmelding: Klarte ikke å sende meldingen.";
}
else{
$msg = "Meldingen har blitt sendt.";
}
$stmt->free_result();
$stmt->close();
$while_count ++;
}
Then I use $msg_receiver_query to asign a value in the query INSIDE the while loop.
What I currently receive in my database is 0 and 1. Nothing else. What would the correct preg_match be for me to output JUST the numbers inside the paranthesis? and is there a more effective solution to this problem of mine?
It looks like you don't want to match, you want to extract just a portion of each $_POST['receiver-check'] value - so preg_replace() would be the right function to use.
$msg_receivers = !empty($_POST['receiver-check']) && is_array($_POST['receiver-check'])
? $_POST['receiver-check'] : array();
$receiverIds = array();
foreach($msg_receivers as $receiver) {
$receiverIds[] = preg_replace('/^.*\((\d+)\)$/', "$1", $reciever);
}
That should give you an array of reciever ids ($receiverIds) like:
array(
[0] => 123,
[1] => 456,
[2] => 789
);
You could do something like this.
This way you can insert it in to your DB. but you will query your Db 3 times to insert 3 records.
<?php
//use your connection Data
$user = "root";
$pass = "***";
$host = "localhost";
$dbdb = "TestDataBase";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//check if receiver-check is set or not
if(isset($_POST['receiver-check'])){
$msg_receivers = $_POST['receiver-check'];
// iterate through $msg_receivers
foreach($msg_receivers AS $value){
preg_match_all("/([0-9]{3})/", $value, $msg_receiver_query);
//Query, just change the table name and columns to what ever you need.
$sql = "INSERT INTO `table` (`column1`) VALUES ('" .$msg_receiver_query[0][0] . "')";
if (mysqli_query($connect, $sql)) {
echo 'Record(s) created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($connect);
}
}
}else{
echo "nothing is set";
}
?>
Maybe a ittle to advanced but you can do this in one query aswell.
<?php
//use your connection Data
$user = "root";
$pass = "***";
$host = "localhost";
$dbdb = "TestDataBase";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//check if receiver-check is set or not
if(isset($_POST['receiver-check'])){
$msg_receivers = $_POST['receiver-check'];
$inputArray = '';
// iterate through $msg_receivers
foreach($msg_receivers AS $value){
preg_match_all("/([0-9]{3})/", $value, $msg_receiver_query);
//insert all output in to an array
$inputArray [] = "('" . $msg_receiver_query[0][0] . "')";
}
//Insert all outputs in 1 query
$sql = "INSERT INTO `testtable` (`column1`) VALUES " . implode(",",$inputArray) . "";
if (mysqli_query($connect, $sql)) {
echo 'Record(s) created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($connect);
}
}else{
echo "nothing is set";
}
?>
the code below extract data from a csv file and insert it in DB. the csv file have 3 columns : title; year; author
The thing is, i don't want to insert the name of the author but his id (check the code to see what i did).
i get the result i want in DB but the server blocks after that.
How can i improve the code so the server will not block.
<?php
if (isset($_POST['submit'])) {
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'database';
$x = 0; // Number of lines added to DB
$isOK = FALSE;
$output = '';
$dsn = 'mysql:dbname='.$db.';host='.$host;
$fh = fopen ($_FILES["file"]["tmp_name"], 'r');
fgetcsv($fh); //to escape the first line in the csv file
try {
$pdo = new PDO($dsn, $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
//for table books :
$sql = 'INSERT INTO `books`(`title`, `year`, `author_id`) ';
$sql .= 'VALUES (?, ?, ?)';
$stmt = $pdo->prepare($sql);
//for table authors :
$sql2 = 'SELECT `author_id` FROM `authors` WHERE `name` = :name';
$stmt2 = $pdo->prepare($sql2);
while (!feof($fh)) {
$books = fgetcsv($fh, 300, ';');
//to get author_id knowing his name **********
$stmt2->execute(array(':name'=>$books[2]));
$row = $stmt2->fetch(PDO::FETCH_ASSOC);
$books[2] = $row['author_id'];
//********************************************
if (isset($books) && is_array($books) && count($books)>0) {
$result = $stmt->execute($books);
$isOK = $result ? TRUE : FALSE;
if(!($isOK)) {
$pdo = NULL;
fclose($fh);
header('Location: ../error.php');
}else {
$x++;
$output .= '<br />INSERTED: ' . $result . ':' . vsprintf('%s | %s | %s ', $books) . PHP_EOL;
}
} else {
$output .= '<br />FAILED : ' . var_export($result, TRUE);
}
}
$pdo = NULL;
} catch(PDOException $e) {
echo '<p><span style="color:red;">Une erreur s\'est produite :</span> '.$e->getMessage().'</p>';
echo '<p>'.$e->getTraceAsString().'</p>';
}
fclose($fh);
} else {
header('Location: import_books_from_csv.php');
}
?>
I got a problem with PDO...
I have this code:
<center>
<?php
/*
$payid = $_GET["payid"];
$data = mysql_connect('localhost','cheapacc_ross2','dsaikoepwq2312','cheapacc_account');
mysql_select_db('cheapacc_account',$data);
$pay1 = mysql_query("SELECT ID,Categorie,Naam,Email,md5_ID FROM acount_Betalingen WHERE md5_ID = '".$payid."' ");
$pay = mysql_fetch_object($pay1);
if($pay){
echo 'betaling is gelukt';
}else{
echo 'Oops jij liegt ons voor?? '.$pay->md5_ID .mysql_error();
}
*/
$flag=0;
require_once '../../include/config.php';
require_once '../../include/processes.php';
$Login_Process = new Login_Process;
$Login_Process->check_status($_SERVER['SCRIPT_NAME']);
$type = base64_decode($_GET["t"]);
$amount = (int)base64_decode($_GET["a"]);
$host = "localhost";
$username = "root";
$password = "20101998";
$dbname = "ross23";
try
{
$db = new PDO("mysql:host=" . $host . ";dbname=" . $dbname, $username, $password);
}
catch(PDOException $e)
{
exit("Error database connection. E: " . $e);
}
$info = $_SESSION['info'];
if(!isset($_GET["t"]) || !isset($_GET["a"]) || !isset($_GET["h"]) || sha1(md5($info)) != $_GET["h"])
{
exit("1: FOUT! / You may not change the url, or you get a ip ban!");
}
if(isset($_GET["t"]) && isset($_GET["a"]) && isset($_GET["h"]) && sha1(md5($info)) == $_GET["h"])
{
$q = $db->query("SELECT COUNT(*) FROM account_" . $type . " ");
$count = $q->fetchColumn();
if($count < $amount)
{
die("Er zijn te weinig accounts voor jouw betaling, meld dit aan de administrator!");
}
for($i = 0; $i < $amount; $i++)
{
$flag=0;
$getid = $db->prepare("SELECT id FROM account_".$type." WHERE used = ?");
$getid->execute( array('0') );
$pid = $getid->fetch();
if($pid[0] == null)
{
exit("Er zijn geen accounts over, meld dit aan de administrator!");
}
$id = $pid[0];
$stmt = $db->prepare("SELECT * FROM account_" . $type . " WHERE id = ? AND used = ?");
$stmt->execute( array($id, '0') );
$result = $stmt->fetch();
if(!$result)
{
exit("2: FOUT! / You may not change the url, or you get a ip ban.");
}
$userinfo = $db->prepare("SELECT userid FROM cw_users WHERE info = ?");
$userinfo->execute( array($info) );
$userinfo = $userinfo->fetch();
$sql = $db->prepare("INSERT INTO account_lijst SET user_id = ? WHERE account = ?");
$sql->execute(array($userinfo[0], $result));
$user_id = $_SESSION['userid'] ;
// query
$sql = "INSERT INTO account_lijst (user_id,soort) VALUES (:user_id,:soort)";
$q = $db->prepare($sql);
$q->execute(array(':author'=>$user_id,
':title'=>$type));
$account_info = explode(":", $result[1]);
$html = "Account Username: " . $account_info[0] . "<br />";
$html .= "Account Password : " . $account_info[1];
$html .= "<br /><br />";
$flag = 1;
if ($flag==1){
$sql = $db->prepare("UPDATE account_" . $type . " SET used = ? WHERE ID = ?");
$sql->execute( array("1", $id) );
echo $html;
}
echo 'test';
}
}
The most of the part works but by INSERT INTO account_lijst
It doesn't works...
But i checked everything but i think everything is fine:S...
Can someone help me with this code please?
*EDIT SQL
CREATE TABLE IF NOT EXISTS `account_lijst` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`account` text NOT NULL,
`date` text NOT NULL,
`soort` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
On your query :
$sql = $db->prepare("INSERT INTO account_lijst SET user_id = ? WHERE account = ?");
$sql->execute(array($userinfo[0], $result));
Try that instead :
$sql = $db->prepare("INSERT INTO account_lijst SET user_id = :user_id WHERE account = :account");
$sql->bindValue(':user_id', $userinfo['0']);
$sql->bindValue(':account', $result);
$sql->execute();
Should work perfectly if the parameters you gave are the good ones?
If you it doesn't can you please dump the parameters used into the query and the table's structure so we can debug deeper? :)
Check your code i guess (probably) there is an error near of this line due to the way you wrote the where clause:
$userinfo = $db->prepare("SELECT userid FROM cw_users WHERE info = ?");
Try this instead:
$userinfo = $db->prepare("SELECT userid FROM cw_users WHERE info = ' ? ' ");
As well in your insert you should use simple apostrophe in ordert o execute that insert:
$sql = $db->prepare("INSERT INTO account_lijst SET user_id = ? WHERE account = ?");
Hope it heps!!