Multiple queries & LastInsertId - php

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();

Related

How last_id works?

The customer sql is inserted the others are not. Help. Thanksss
I have sql for customer_tbl, transaction_tbl, and order_tbl.
customer_no, transaction_no and orderlist_no are A_I.
This is my code so far.
$x=0;
while ($x!=5) {
$product_sku[$x] = $_POST['productsku[$x]'];
$quantity[$x] = $_POST['productqty[$x]'];
$x=$x+1;
}
$sqlc = "INSERT INTO customer_tbl(customer_name, fb_url, mobile_no, email_address, address) VALUE ('$customer_name', '$fb_url', '$mobile_no', '$email', '$address');";
mysqli_query($conn, $sqlc);
$last_id = mysqli_insert_id($conn);
$sqlt = "INSERT INTO transaction_tbl(customer_no, transaction_type, status, transaction_date, deadlinepay_date, payment_mode, delivery_option) VALUE ('$lastid', 'OL-', '1', CURRENT_TIMESTAMP(), '$deadlinepay_date', '$payment_mode', '$shipping_option');";
mysqli_query($conn, $sqlt);
$last_id = mysqli_insert_id($conn);
$x=0;
while ($x!=5) {
if (!empty($product_sku[$x])) {
$sqlo = "INSERT INTO order_tbl(transaction_no, product_sku, quantity) VALUES ('$last_id', '$product_sku', '$quantity');";
mysqli_query($conn, $sqlio);
}
$x=$x+1;
}
In your code, you have $last_id = mysqli_insert_id($conn); but in your query, you have ...VALUE ('$lastid'....
So change $lastid to $last_id or the other way around.
You should keep naming your variables consistent to avoid confusion in the future.

How to check if a table exists in MySQL using PHP PDO? [duplicate]

This question already has answers here:
Check if MySQL table exists without using "select from" syntax?
(19 answers)
Closed 5 years ago.
if($count <= 0 ) // IF TABLE DOES NOT EXIST -> CREATE AND INSERT DATA
{
$CREATE_TABLE= "CREATE TABLE $TABLE_NAME LIKE student; INSERT $TABLE_NAME SELECT * FROM student;";
$created = $connect->exec($CREATE_TABLE);
if($created!=FALSE)
{
$SQL = "INSERT INTO $TABLE_NAME (name, roll_number, father_name, dob, gender, address, email, phone, department, program, semester, section) VALUES(:name, :roll_number, :father_name, :dob, :gender, :address, :email, :phone, :department, :program, :semester, :section)";
$pdo_statement = $connect->prepare($SQL);
$pdo_statement->bindparam(':name', $name);
$pdo_statement->bindparam(':roll_number', $roll_number);
$pdo_statement->bindparam(':father_name', $father_name);
$pdo_statement->bindparam(':dob', $dob);
$pdo_statement->bindparam(':gender', $gender);
$pdo_statement->bindparam(':address', $address);
$pdo_statement->bindparam(':email', $email);
$pdo_statement->bindparam(':phone', $phone);
$pdo_statement->bindparam(':department', $department);
$pdo_statement->bindparam(':program', $program);
$pdo_statement->bindparam(':semester', $semester);
$pdo_statement->bindparam(':section', $section);
$result = $pdo_statement->execute();
}
}
else if($count > 0) // IF TABLE EXIST -> INSERT DATA
{
$SQL = "INSERT INTO $TABLE_NAME (name, roll_number, father_name, dob, gender, address, email, phone, department, program, semester, section) VALUES (:name, :roll_number, :father_name, :dob, :gender, :address, :email, :phone, :department, :program, :semester, :section)";
$pdo_statement = $connect->prepare($SQL);
$pdo_statement->bindparam(':name', $name);
$pdo_statement->bindparam(':roll_number', $roll_number);
$pdo_statement->bindparam(':father_name', $father_name);
$pdo_statement->bindparam(':dob', $dob);
$pdo_statement->bindparam(':gender', $gender);
$pdo_statement->bindparam(':address', $address);
$pdo_statement->bindparam(':email', $email);
$pdo_statement->bindparam(':phone', $phone);
$pdo_statement->bindparam(':department', $department);
$pdo_statement->bindparam(':program', $program);
$pdo_statement->bindparam(':semester', $semester);
$pdo_statement->bindparam(':section', $section);
$result = $pdo_statement->execute();
} // ELSE IF ENDS
So i understand you will create the table, if it does not exist and insert data. So call first
$pdo->query("CREATE TABLE $TABLE IF NOT EXISTS;");
It will do nothing, when table exists.
And then insert your data.
$pdo->query("INSERT INTO $TABLE ... ");
No 'if then else' in PHP!
function tableExists($pdo, $table) {
// Try a select statement against the table
// Run it in try/catch in case PDO is in ERRMODE_EXCEPTION.
try {
$result = $pdo->query("SELECT 1 FROM $table LIMIT 1");
} catch (Exception $e) {
// We got an exception == table not found
return FALSE;
}
// Result is either boolean FALSE (no table found) or PDOStatement Object (table found)
return $result !== FALSE;
}

PHP/SQL Multi INSERT INTO dont work

I cant insert 2 tabs at once.
It only insert 1 of them (In this example, it inserts the first one)
function addNewUser($username, $password, $email){
$time = time();
/* If admin sign up, give admin user level */
if(strcasecmp($username, ADMIN_NAME) == 0){
$ulevel = ADMIN_LEVEL;
}else{
$ulevel = USER_LEVEL;
}
$datumregistrationbla = date("d.m.Y");
$q = "INSERT INTO ".TBL_USERS." (username, password, email, userlevel, register_date) VALUES ('$username', '$password', '$email', '$ulevel', '$datumregistrationbla')";
return mysql_query($q, $this->connection);
$q = "INSERT INTO `post` (`post_id`, `from`, `to`, `betreff`, `text`, `datum`, `active`) VALUES ('', 'Fuchsfeuer', '$username', 'Test', 'Test2', '$datumregistrationbla', '0')";
return mysql_query($q, $this->connection);
}
The problem is because you return the first mysql_query and the rest will not be executed.Try removing it like this.
function addNewUser($username, $password, $email){
$time = time();
/* If admin sign up, give admin user level */
if(strcasecmp($username, ADMIN_NAME) == 0){
$ulevel = ADMIN_LEVEL;
}else{
$ulevel = USER_LEVEL;
}
$datumregistrationbla = date("d.m.Y");
$q = "INSERT INTO ".TBL_USERS." (username, password, email, userlevel, register_date) VALUES ('$username', '$password', '$email', '$ulevel', '$datumregistrationbla')";
mysql_query($q, $this->connection);
$q = "INSERT INTO `post` (`post_id`, `from`, `to`, `betreff`, `text`, `datum`, `active`) VALUES ('', 'Fuchsfeuer', '$username', 'Test', 'Test2', '$datumregistrationbla', '0')";
mysql_query($q, $this->connection);
}
Please forget using mysql_* because it is deprecated and in php 7 it was already removed.
Try to use mysqli or pdo

Insert stmt with a Select and additional Params

Is it possible to have a "mixed" SQL Insert like the following?
I want to be able to get one value from another table (that needs a param) and then enter in 2 more params.
$sql = "INSERT INTO tblquestions (userID, questionText, questionAnswer) VALUES (
Select userID FROM tblusers WHERE userEmail = (?),?,?)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'sss', $userEmail, $question, $answer);
$result = mysqli_stmt_execute($stmt);
if (!$result) {
throw new Exception($conn->error);
}
It is unnecessary. Just use insert . . . select:
INSERT INTO tblquestions(userID, questionText, questionAnswer)
Select userID, ?, ?
FROM tblusers
WHERE userEmail = (?);

using bindParam with PDO

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.

Categories