How last_id works? - php

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.

Related

php mysqli insert data into two tables

I'm trying to insert data into 2 tables in php mysqli but it inserts data in the first table fine but not inserting anything in the second where there are other columns as well in the second table.
Here is my code:
$sql = "INSERT INTO socio (name, age, dob, gender, year, stgroup, stadd) VALUES ('$stnam', '$stage', '$stdob', '$stgen', '$styer', '$stGr', '$stadd')";
$sql1 = "INSERT INTO parta (name, stgroup, year) VALUES ('$stnam', '$stGr', '$styer')";
$result = mysqli_query($con, $sql);
$result = mysqli_query($con, $sql1);
Is anything wrong in the above code? Any suggestions?
I can't really see what's exactly wrong with your code, it might happen that some of the columns on the parta table are not supposed to be null. With the code you provided, it's hard to tell, as there's no error handling at all. You might want to use transactions, then use proper error handling and also use prepared statements.
Try with this code that I have prepared for you.
<?php
$con = new mysqli("..."); // you should know this part already
$success = false;
try {
$con->autocommit(FALSE);
$con->begin_transaction();
if ($sql = $con->prepare("INSERT INTO socio (name, age, dob, gender, year, stgroup, stadd) VALUES (?,?,?,?,?,?,?)")) {
$sql->bind_param('sissss', $stnam, $stage, $stdob, $stgen, $styer, $stGr, $stadd);
if (!$sql->execute()) {
throw new Exception($sql->error);
}
if ($sql_two = $con->prepare("INSERT INTO parta (name, stgroup, year) VALUES (?,?,?)")) {
$sql_two->bind_param('sss', $stnam, $stGr, $styer);
if (!$sql_two->execute()) {
throw new Exception($sql_two->error);
}
}
}
if ($con->commit()) {
$success = true;
} else {
throw new Exception('Transaction commit failed...');
}
}catch (Exception $ex) {
try {
// something went wrong,rollback and display message
$con->rollback();
echo $ex->getMessage();
}
catch (Exception $e) {
echo $e->getMessage();
}
}
$con->autocommit(TRUE);
if ($success) {
echo "data successfully inserted";
}
?>
Try this. It could be because you have the same variable name for two different actions. I've just rename the second result as $result1
$sql = "INSERT INTO socio (name, age, dob, gender, year, stgroup, stadd) VALUES ('$stnam', '$stage', '$stdob', '$stgen', '$styer', '$stGr', '$stadd')";
$sql1 = "INSERT INTO parta (name, stgroup, year) VALUES ('$stnam', '$stGr', '$styer')";
$result = mysqli_query($con, $sql);
$result1 = mysqli_query($con, $sql1);

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

Error Column count doesn't match value count at row 1?

where is error.....
Column count doesn't match value count at row 1
mysqli_select_db($conn, $data);
$save = "INSERT INTO SONG_AS(ALBUM, CATEGORY, SUB_CATEGORY,
SONG_NAME, ARTIST, ART_LINK,
YEAR, GENRE, SONG_LINK, POST_ON,
POST_BY, TOTAL_DOWNLOAD)
VALUES('$albm', '$cat', '$scat', "
. "'$sn', '$art', '$img', "
. "'$y', '$g', "
. "'$sl', '$time', '', '0')";
$success = mysqli_query($conn, $save) or die(mysqli_error($conn));
$page = "index.php";
$this->pageRedirect($page);
where is error.....
Column count doesn't match value count at row 1
remove '' from your query to be:
$save = "INSERT INTO SONG_AS(ALBUM, CATEGORY, SUB_CATEGORY,
SONG_NAME, ARTIST, ART_LINK,
YEAR, GENRE, SONG_LINK, POST_ON,
POST_BY, TOTAL_DOWNLOAD)
VALUES('$albm', '$cat', '$scat','$sn', '$art', '$img', '$y', '$g', '$sl', '$time', '', '0')";
Try this:
$save = "INSERT INTO SONG_AS(`ALBUM`, `CATEGORY`, `SUB_CATEGORY`,
`SONG_NAME`, `ARTIST`, `ART_LINK`,
`YEAR`, `GENRE`, `SONG_LINK`, `POST_ON`,
`POST_BY`, `TOTAL_DOWNLOAD`)
VALUES('".$albm."', '".$cat."', '".$scat."','".$sn."', '".$art."', '".$img."', '".$y."', '".$g."', '".$sl."', '".$time."', '', '0')";
$query = "INSERT INTO employee VALUES ($empno','$lname','$fname','$init','$gender','$bdate','$dept','$position','$pay','$dayswork','$otrate','$othrs','$allow','$advancesance,'')";
$msg = "New record saved!";
}
else {
$query = "UPDATE employee SET empno=$empno','lname='$lname',fname='$fname',init= '$init',gender='$gender',bdate='$bdate',dept='$dept',position='$position',pay=$pay,dayswork=$dayswork,otrate=$otrate,othrs=$othrs,allow=$allow,advances=$advances,insurance=$insurance WHERE empno = $empno";
$msg = "Record updated!";
}

why does php mysql update returns a success but never updated the column?

my basic goal is to update a single row and if it is successful it will insert some data in different table.
here is my query
$upd = mysql_query("UPDATE request_tbl SET status='1' WHERE sender='$user_id' AND reciever='$id'", $con);
if($upd){
$result = mysql_query("INSERT INTO contact_tbl (id, friend_id) VALUES ('$user_id', '$id')", $con);
$result2 = mysql_query("INSERT INTO contact_tbl (id, friend_id) VALUES ('$id', '$user_id')", $con);
if($result && $result2){
$jsonresult = $myFunctions->jsonRequest("Sent Request");
}
else{
$jsonresult = $myFunctions->jsonRequest("Failed Request");
}
}
note: the scenario is i am updating data to the webserver using android app,
when i try to test the query from using this.
http://----/-----.php?req=accept&user-id=5&id=1
i get a success message and updates, and insert the data in the database. However when i try to send the request from the app it returns a success message and inserts the data, that means that the update was successful but in the database it was never update.
i also tried to change the data type of the column status to int or varchar but still with the same effect, it is weird the insert was excuted but the update was never happened or it was?
EDIT ! ! !
i did try all the recommended solutions like mysql_affected_rows() > 0 and echoing the query but with no luck.. as everyone recommends/insits :) i will try to convert the query into PDO or mysqli thanks for the help everyone.
**EDIT 2 ! ! ! **
i tried to to convert my queries to PDO
here is my code
$upd = $con->prepare("UPDATE request_tbl SET `status`='1' WHERE `sender`='$user_id' AND `reciever`='$id' AND `status`='0'");
try{
$upd->execute();
$result = $con->prepare("INSERT INTO contact_tbl (id, friend_id) VALUES (?, ?)");
$result->bindParam(1, $user_id);
$result->bindParam(2, $id);
$result2 = $con->prepare("INSERT INTO contact_tbl (id, friend_id) VALUES (?, ?)");
$result2->bindParam(1, $id);
$result2->bindParam(2, $user_id);
try{
$result->execute();
$result2->execute();
$jsonresult = $myFunctions->jsonRequest("Sent Request");
}
catch(PDOException $e){
$jsonresult = $myFunctions->jsonRequest("Failed Request");
}
}
catch(PDOException $e){
$jsonresult = $myFunctions->jsonRequest("Failed Request");
}
echo $jsonresult;
but i recieve the same result, whenever i try it using the url method the update and insert are successful with the correct value, but when i do it with the app the update and insert returns successful and the insert have the correct value but the update did not change the column im changing..
use mysql_affected_rows() to check how many rows were affected. Try this,
if(mysql_affected_rows()){
// your stuff here.
}
try this folk, use mysql_num_rows(). mysql_affected_rows() give you a nums of rows afected by the last query executed. and you know how manny rows are afected. Hope this can help you
$upd = mysql_query("UPDATE request_tbl SET status='1' WHERE sender='$user_id' AND reciever='$id'", $con);
$NumsRowsAfected = mysql_affected_rows();
if(mysql_affected_rows() > 0){
$result = mysql_query("INSERT INTO contact_tbl (id, friend_id) VALUES ('$user_id', '$id')", $con);
$result2 = mysql_query("INSERT INTO contact_tbl (id, friend_id) VALUES ('$id', '$user_id')", $con);
if($result && $result2){
$jsonresult = $myFunctions->jsonRequest("Sent Request");
}
else{
$jsonresult = $myFunctions->jsonRequest("Failed Request");
}
}
Make sure that values of $user_id and $id getting on the current page you are in.
Hopefully, you passed the user id variable as user-id and retrieved as $_GET['user-id'].
If its perfect then, echo both queries and run the printed query on phpmyadmin manually. That will through the erroe
echo $result = mysql_query("INSERT INTO contact_tbl (id, friend_id) VALUES ('$user_id', '$id')", $con);
echo $result2 = mysql_query("INSERT INTO contact_tbl (id, friend_id) VALUES ('$id', '$user_id')", $con);
more over mysql_query has been deprecated. Those functions will be no more exist. Try PDO or MySQLi

Multiple queries & LastInsertId

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

Categories