I've been scratching my head over this code for a couple of hours....
Doesn't make sense to me why it doesn't work
$isCorrect =($question->correct_answer == $body->answer) ? 1:0;
// the values are all there.......
// echo $body->question . "\n"; //335
// echo $body->user . "\n"; //51324123
// echo $question->day . "\n"; //0
// echo $isCorrect . "\n"; //0
//but still the below part fails.
$db = getConnection();
$sql = "INSERT INTO `answers` (`id`, `question_id`, `user`, `day`, `is_correct`) VALUES (NULL, ':question', ':user', ':day', :is_correct)";
$stmt = $db->prepare($sql);
$stmt->bindParam(":question_id", $body->question);
$stmt->bindParam(":user", $body->user);
$stmt->bindParam(":day", $question->day, PDO::PARAM_INT);
$stmt->bindParam(":is_correct", $isCorrect, PDO::PARAM_INT);
$stmt->execute();
gives this error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
I'm counting 4 tokens... what am I missing? Obviously I'm doing something wrong.
Try it like this:
$sql = "INSERT INTO `answers` (`id`, `question_id`, `user`, `day`, `is_correct`)
VALUES
--The :variable shouldn't be surrounded by ''--
(NULL, :question, :user, :day, :is_correct)";
$stmt = $db->prepare($sql);
//The values used in $sql should be the same here, so not :question_id but :question
$stmt->bindParam(":question", $body->question);
$stmt->bindParam(":user", $body->user);
$stmt->bindParam(":day", $question->day, PDO::PARAM_INT);
$stmt->bindParam(":is_correct", $isCorrect, PDO::PARAM_INT);
just don't use bindParam with PDO
as well as named parameters. it will save you a ton of headaches
$db = getConnection();
$sql = "INSERT INTO `answers` VALUES (NULL, ?,?,?,?)";
$data = [$body->question,$body->user,$question->day,$isCorrect];
$stmt = $db->prepare($sql)->execute($data);
change :
$stmt->bindParam(":question_id", $body->question);
to:
$stmt->bindParam(":question", $body->question);
You have use in query :question but binding with wrong key(:question_id).
$stmt->bindParam(":question_id", $body->question);
should be
$stmt->bindParam(":question", $body->question);
This is just a little typo.
Related
I'm trying to convert mysqli to PDO but I'm getting one string empty, all the rest is fine.
My code mysqli:
$sql="SELECT uid FROM userprofile WHERE `name` = '$_POST[name]'";
$result=mysqli_query($con,$sql);
if($result&&mysqli_num_rows($result)>0){
$dwID = mysqli_fetch_array($result);
$time=time().'000';
$time1=time();
switch($_POST['t3']){
case ''.$mail_9.'':{
$b=bin2hex($_POST['type1'].','.$_POST['ts1'].','.$_POST['ts2']);
$b1=($_POST['type1'].','.$_POST['ts1'].','.$_POST['ts2']);
mysqli_query($con,"INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, status, type, rewardStatus, saveFlag, createTime, reply) VALUES (md5($time), '$dwID[0]','$_POST[titlegift]','$_POST[titlegift]', 0x$b,'1','0','13','0','0','$time','0')")or die('2');
And now I'm trying to converto to PDO like this:
$sql = "SELECT * from userprofile where `uid`='$_POST[name]'";
$query = $dbh2 -> prepare($sql);
$query->execute();
$result=$query->fetch(PDO::FETCH_OBJ);
$cnt=1;
$uid = $query->$result;
$time = time().'000';
$gifttitle = $_POST['gifttitle'];
$b = bin2hex($_POST['type1'].','.$_POST['itemid'].','.$_POST['quantity']);
$sql1 = "INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, `status`, `type`, rewardStatus, saveFlag, creatTime, reply) VALUES (md5($time), '$uid', '$_POST[gifttitle]', '$_POST[gifttitle]', 0x$b, '1', '0', '13', '0', '0', '$time', '0')";
$query = $dbh2 -> prepare($sql1);
$query -> execute();
But when I run var_dump (SQL) it add all the fields and only $uid is empty.
Sorry for the code mysqli I know it is a messy.
This is wrong:
$uid = $query->$result;
$result is an object containing the row that was fetched from the table. It's not the name of a property of the $query object.
That should be:
$uid = $result->uid;
You should also use a prepared statement rather than substituting variables into the SQL string.
$sql1 = "INSERT INTO mail (uid, toUser, title, contents, rewardId, itemIdFlag, `status`,
`type`, rewardStatus, saveFlag, creatTime, reply)
VALUES (md5(:time), :uid, :gifttitle, :gifttitle, UNHEX(:rewardid), '1', '0',
'13', '0', '0', :time, '0')";
$query = $dbh2 -> prepare($sql1);
$query->bindParam(':time', $time);
$query->bindParam(':uid', $uid);
$query->bindParam(':rewardid', $b);
$query->bindParam(':gifttitle', $_POST['gifttitle']);
$query->execute();
Next code gives me an error SQLSTATE[HY093]: Invalid parameter number
$sql = "INSERT INTO `users` (`id`, `date_install`, `date_ping`, `cc`, `uv`, `pid`, `pv`, `aff_id`, `sub_id`, `channel`, `cid`, `os`, `av`, `db`) VALUES (:id, :date_install, now(), :country, :updaterVersion, :productId, :productVersion, :affiliateId, :subId, :channel, :commandId, :os, :av, :defaultBrowser) "
. "ON DUPLICATE KEY UPDATE `date_install` = :date_install, `date_ping` = now(), `cc` = :country, `uv` = :updaterVersion, `pid` = :productId, `pv` = :productVersion, `aff_id` = :affiliateId, `sub_id` = :subId, `channel` = :channel, `cid` = :commandId, `os` = :os, `av` = :av, `db` = :defaultBrowser ";
$statement = $database->prepare($sql);
$statement->bindValue(":id", $user->id, PDO::PARAM_INT);
$statement->bindValue(":date_install", $user->date_install, PDO::PARAM_STR);
$statement->bindValue(":country", $user->cc, PDO::PARAM_STR);
$statement->bindValue(":updaterVersion", $user->uv, PDO::PARAM_INT);
$statement->bindValue(":productId", $user->pid, PDO::PARAM_INT);
$statement->bindValue(":productVersion", $user->pv, PDO::PARAM_INT);
$statement->bindValue(":affiliateId", $user->aff_id, PDO::PARAM_INT);
$statement->bindValue(":subId", $user->sub_id, PDO::PARAM_INT);
$statement->bindValue(":channel", $user->channel, PDO::PARAM_STR);
$statement->bindValue(":commandId", $user->cid, PDO::PARAM_INT);
$statement->bindValue(":os", $user->os, PDO::PARAM_STR);
$statement->bindValue(":av", $user->av, PDO::PARAM_STR);
$statement->bindValue(":defaultBrowser", $user->db, PDO::PARAM_STR);
$statement->execute();
I have no idea what is wrong and if I copy/paste SQL into console and replace all values manually everything works. Also if I comment out part ON DUPLICATE KEY..., also works.
If emulation mode is turned off for your PDO instance, you won't be able to use the same placeholder name more than once in the query.
Besides, for the ON DUPLICATE it is not necessary either, as you can always use the VALUES operator that will take the value from the VALUES clause:
ON DUPLICATE KEY UPDATE `date_install` = VALUES(date_install), ...
PDO Doesn't allow repetition of variable names. Your ON DUPLICATE KEY UPDATE should have it's own variable names. Which also means you have to assign your variables 2 times. This is a sad limitation :(.
In order to use the same parameter names twice, you must set PDO::ATTR_EMULATE_PREPARES attribute to true:
$database->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
I'am trying to insert in my two table at once
but i keep getting this error
Invalid parameter number: number of bound variables does not match number of tokens :
$dbh->beginTransaction();
try{
if(sizeof($return['error'])==0){
$sql = "INSERT INTO circle_call_prefixes (circle, prefix)
VALUES (?,?)";
$q = $dbh->prepare($sql);
$q ->execute(array('123', '123'));
$Last_ID = $dbh->lastInsertId();
$sql_table2 = "INSERT INTO circle_call_destinations
(autoNo,destination, source_circle) VALUES (?,?,?)";
$q = $dbh->prepare($sql);
$q -> execute(array($Last_ID, '123', '123'));
$dbh->commit();
}
what is the possible problem? thanks
You try to run in both cases $sql, but should run in second case $sql_table2. This code should works:
$dbh->beginTransaction();
try{
if(sizeof($return['error'])==0){
$sql = "INSERT INTO circle_call_prefixes (circle, prefix)
VALUES (?,?)";
$q = $dbh->prepare($sql);
$q ->execute(array('123', '123'));
$Last_ID = $dbh->lastInsertId();
$sql_table2 = "INSERT INTO circle_call_destinations
(autoNo,destination, source_circle) VALUES (?,?,?)";
$q = $dbh->prepare($sql_table2);
$q -> execute(array($Last_ID, '123', '123'));
$dbh->commit();
}
I am pretty new to SQL Transactions and tried to execute following statement which did unfortunately not work...
$stmt = $mysqli->prepare("
BEGIN;
INSERT INTO groups (group_name, group_desc, user_id_fk) VALUES ("'.$groupName.'","'.$groupDesc.'","'.$user_id.'");
INSERT INTO group_users (group_id_fk, user_id_fk) VALUES (LAST_INSERT_ID(), "'.$username.'");
COMMIT;
") or trigger_error($mysqli->error, E_USER_ERROR);
$stmt->execute();
$stmt->close();
Is this even possible what I am trying here or is it completely wrong?
I appreciate every response, thank you!
You are using prepare() wrong way. There is absolutely no point in using prepare() if you are adding variables directly in the query.
This is how your queries have to be executed:
$mysqli->query("BEGIN");
$sql = "INSERT INTO groups (group_name, group_desc, user_id_fk) VALUES (?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssi",$groupName,$groupDesc,$user_id);
$stmt->execute();
$sql = "INSERT INTO group_users (group_id_fk, user_id_fk) VALUES (LAST_INSERT_ID(), ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$username);
$stmt->execute();
$mysqli->query("COMMIT");
How wrong is that query? Can I insert multiple queries like that?
Can I use lastInsertId like that?
$pdo = Database::connect();
$dflt = 'DEFAULT';
$query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, '$hashed_password', :nome, :dt_registo, :tipo, :activo)";
$stmt = $pdo->prepare($query1);
$stmt->execute();
$insertedid = $pdo->lastInsertId("utilizador");
$query2 ="INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
VALUES (:morada, :cpostal, :cidade,'$insertedid')";
$stmt2 = $pdo->prepare($query2);
$stmt2->execute();
$hashed_password = hash( 'sha512', $_POST['password']);
$stmt->bindParam(':email',$_POST['email']);
$stmt->bindParam(':nome',$_POST['nome']);
$stmt->bindParam(':dt_registo',$dflt);
$stmt->bindParam(':tipo',$dflt);
$stmt->bindParam(':activo',$dflt);
$stmt->bindParam(':morada',$_POST['morada']);
$stmt->bindParam(':cpostal',$_POST['cpostal']);
$stmt->bindParam(':cidade',$_POST['cidade']);
if($stmt->execute()){
echo "Product was created.";
}else{
echo "Unable to create product.";
}
Database::disconnect();
}
catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
I've already been searching but couldn't find how to use both in a query and I already expired all the solutions, not sure which is wrong.
EDIT:
I'm starting to think its more than the query, if someone notice something..
JAVASCRIPT
$(document).on('submit', '#create-aluno-form', function() {
// show a loader img
$('#loader-image').show();
// post the data from the form
$.post("registar.php", $(this).serialize())
.done(function(data) {
// show create product button
$('#create-aluno').show();
showProducts();
});
return false;
});
Most likely your statement fails to insert, Your code is full of problems:
You used prepare statement but yet you put values in the query string
hashed_password is undefined in the first query
You try to bind multiple queries at once
wrong order prepare the first query, execute , then bind the parameters
-$pdo->lastInsertId(); is enough not sure why you pass "utilizador"
Try this approach:
try{
$pdo = Database::connect();
$dflt = 'DEFAULT';
$hashed_password = hash( 'sha512', $_POST['password']);
$query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, :pass, :nome, :dt_registo, :tipo, :activo)";
$stmt = $pdo->prepare($query1);
$stmt->bindParam(':email',$_POST['email']);
$stmt->bindParam(':pass',$hashed_password);
$stmt->bindParam(':nome',$_POST['nome']);
$stmt->bindParam(':dt_registo',$dflt);
$stmt->bindParam(':tipo',$dflt);
$stmt->bindParam(':activo',$dflt);
if($stmt->execute()){
//query1 success
$insertedid = $pdo->lastInsertId();
$query2 ="INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
VALUES (:morada, :cpostal, :cidade, :utilizador_id)";
$stmt2 = $pdo->prepare($query2);
$stmt2->bindParam(':morada',$_POST['morada']);
$stmt2->bindParam(':cpostal',$_POST['cpostal']);
$stmt2->bindParam(':cidade',$_POST['cidade']);
$stmt2->bindParam(':utilizador_id',$insertedid);
if($stmt2->execute()){
//query2 success
}else{
//query2 failed
}
}else{
//query1 failed
}
Database::disconnect();
}
catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
Try this....
$query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, '$hashed_password', nome, :dt_registo, :tipo, :activo);";
$stmt = $pdo->prepare($query1);
$stmt->execute();
$query2 ="INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
VALUES (:morada, :cpostal, :cidade, LAST_INSERT_ID());";
$stmt2 = $pdo->prepare($query2);
$stmt2->execute();
Because insert the query not get last insert id. so separate those queries
You have to use the
mysql_insert_id()
to get the last inserted record's id
I think these will useful to you.
$query = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, '$hashed_password', nome, :dt_registo, :tipo, :activo)";
$query_1 = " INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
VALUES (:morada, :cpostal, :cidade, mysql_insert_id())";
$stmt = $pdo->prepare($query);
$stmt_1 = $pdo->prepare($query_1);
these will useful to you.
mysql_select_db('test');
mysql_query("INSERT INTO mytable (name) values ('venkatesh')");
printf("Last inserted record has id %d\n", mysql_insert_id());
Thank you.
see here
INSERT INTO questions VALUES(NULL, 'My question');
INSERT INTO answers VALUES(NULL, LAST_INSERT_ID(), 'Answer 1');
INSERT INTO answers VALUES(NULL, LAST_INSERT_ID(), 'Answer 2');
INSERT INTO answers VALUES(NULL, LAST_INSERT_ID(), 'Answer 3');
Now I Have using LAST_INSERT_ID();
INSERT INTO answers VALUES
(NULL, LAST_INSERT_ID(), 'Answer 1') ,
(NULL, LAST_INSERT_ID(), 'Answer 2') ,
(NULL, LAST_INSERT_ID(), 'Answer 3');
OR
also we can try this way
INSERT INTO questions VALUES(NULL, 'My question');
SET #id = (SELECT LAST_INSERT_ID());
INSERT INTO answers VALUES(NULL, #id, 'Answer 1');
INSERT INTO answers VALUES(NULL, #id, 'Answer 2');
INSERT INTO answers VALUES(NULL, #id, 'Answer 3');
It was just an example for you
$query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, '$hashed_password', nome, :dt_registo, :tipo, :activo);";
$stmt = $pdo->prepare($query1);
$stmt->execute();
$insertedid = $pdo->lastInsertId("utilizador");
$query2 ="INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
Ref link:-http://www.dreamincode.net/forums/topic/169597-pdolastinsertid/
VALUES (:morada, :cpostal, :cidade,'$insertedid'
);";
$stmt2 = $pdo->prepare($query2);
$stmt2->execute();