Why does PDO::lastInsertId return 0? - php

This is my code.
// insert reward into wallet
$sql = "
INSERT INTO `wallet` (`uid`, `created_at`, `amount`, `type`, `payment_id`) VALUES (:uid, CURRENT_TIMESTAMP, :amount, 'payment', :payment_id);
";
$sth = self::link()->prepare($sql);
// primary key makes sure payment does not get double rewarded
$sth->execute(
array(
':uid' => $referer,
':amount' => $reward,
':payment_id' => $payment_data['payment_id'],
)
);
var_dump(self::link()->errorInfo());
self::log("issuing subscription",self::LOG_LEVEL_DEBUG);
// extend referers subscription
$tid = self::link()->lastInsertId();
var_dump(self::link()->errorInfo());
self::log("using $tid as id for wallet transfer",self::LOG_LEVEL_DEBUG);
My log says:
[2011-07-02 20:31:44] using 0 as id for wallet transfer
However the insert query is successful, the database record is created and both errorInfo outputs give no error.

Remove the semicolon or the whitespace after the semicolon or both from your query:
$sql = "
INSERT INTO `wallet` (`uid`, `created_at`, `amount`, `type`, `payment_id`) VALUES (:uid, CURRENT_TIMESTAMP, :amount, 'payment', :payment_id)
";

Related

INSERT into mysql DATABASE Prepared Statments

Can anybody see why this is not inputting into my database..
I did have it working, but now i got the error on mysql A form on this field has more than 1000 fields, but none of them do....
here is the prep statment
$db = new PDO("mysql:host=localhost;dbname=class2", 'root', '');
$query="INSERT INTO `testdata` (`1st name`, `2nd name`, `title`, `info`, `location`, `phone`, `postcode`, `image`, `image2`, `image3`, `image4`, `image5`, `price`, `catagory`, `cond`, `delivery`, `email`, `username`, `youtubevideo`, `paypal`, `facebook`, `twitter`, `feedbackscore`)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$stat=$db->prepare($query);
$stat->execute(array("$firstname","$lastname","$sellingtitle","$sellinginfo","$town","$phone1","$postcode","$i0url","$i1url","$i2url","$i3url","$i4url","$price","$catagory","$cond","$delivery","","$sellername","$youtubeurl","$paypal","$facebook","$twitter","feedbackscore"));
Your PDO is not prepared correctly.
$database = new PDO("mysql:host=localhost;dbname=class2", 'root', '');
$query = "UPDATE users SET first_name = :first_name, last_name = :last_name
WHERE user_id = :user_id";
$update = $database->prepare($query);
$update->execute([
':first_name' => $_POST['firstname'],
':last_name' => $_POST['lastname'],
':user_id' => $_SESSION['user_id']
]);
$update->fetch();
With PDO you define the keys of the values in the prepare string like :first_name.
So then in the execute function's array, you define the values of these keys.
Hope it helps.

xampp MySQL Ignore - how to catch errors in PHP file

I'm new in using transaction. My previous problem is about multiple inserts that should abort if one encounters an error and transaction with ignore solves it. My new problem is that I have to know if the insert is successful and if not should display the error.
PROFILE table
+--+----+---------+
|ID|NAME|BAL_LIMIT|
+--+----+---------+
NUMBER table
+--+----------+------+
|ID|PROFILE_ID|NUMBER|
+--+----------+------+
--TRANSACTION STATEMENT--
START TRANSACTION;
INSERT IGNORE INTO `PROFILE` (`ID`, `NAME`, `BAL_LIMIT`) VALUES(NULL, "Name", 0);
INSERT INTO `NUMBER` (`PROFILE_ID`, `NUMBER`) VALUES(LAST_INSERT_ID() , "09123456789");
COMMIT;
--ERROR TO BE HANDLED--
#1062 - Duplicate entry '09123456789' for key 'NUMBER_UNIQUE'
--PHP file contains--
$vname = $_POST["iname"];
$vbalancelimit = $_POST["ibalancelimit"];
$vnumber = $_POST["inumber"];
$transaction = "START TRANSACTION;
INSERT IGNORE INTO `PROFILE` (`ID`, `NAME`, `BAL_LIMIT`) VALUES(NULL, \"$vname\", $vbalancelimit);
INSERT INTO `NUMBER` (`ID`, `PROFILE_ID`, `NUMBER`) VALUES(NULL, LAST_INSERT_ID(), \"$vnumber\");
COMMIT;";
$execute_transaction = mysqli_multi_query($con,$transaction) or die("Error: ".mysqli_error($connection));
if (!$execute_transaction) {
echo mysqli_error($connection);
} else { echo "success"; }
The PHP file always shows success though having #1062 error and the inserts are ignored.
Multi-queried transaction statement problem solved.
Final PHP file:
<?php
$vname = $_POST["iname"];
$vbalancelimit = $_POST["ibalancelimit"];
$vnumber = $_POST["inumber"];
$transaction = "
START TRANSACTION;
INSERT IGNORE INTO `PROFILE` (`ID`, `NAME`, `BAL_LIMIT`) VALUES(NULL, \"$vname\", $vbalancelimit);
INSERT INTO `NUMBER` (`ID`, `PROFILE_ID`, `NUMBER`) VALUES(NULL, LAST_INSERT_ID(), \"$vnumber\");
COMMIT;";
$aff_rows = 0;
if(mysqli_multi_query($con,$transaction)){
do{$aff_rows+=mysqli_affected_rows($con);
}while(mysqli_more_results($con) && mysqli_next_result($con));
}if($aff_rows==2){//SUCCESS
echo "<script>swal(\"$vname\", \"New number: $vnumber\", \"success\");</script>";
}if($aff_rows==1){//WRONG NUMBER CORRECT NAME
echo "<script>swal(\"Duplicate entry of $vnumber\", \"Failed to add for: $vname\", \"error\");</script>";
}if($aff_rows==0){//WRONG NAME CORRECT/WRONG NUMBER
echo "<script>swal(\"Duplicate entry of $vname\", \"Failed to add number: $vnumber\", \"error\");</script>";}
?>

Prepared sql request INSERT INTO a variable table

I'm trying to execute a prepared sql request wich should insert values into a variable table
This code will be more explicite than me :
$req = $db->prepare("INSERT INTO ?
( `id`,
`parent_id`,
`position`,
`left`,
`right`,
`level`,
`title`,
`type`,
`content` )
VALUES (NULL,
'2',
'last',
'3',
'10',
'2',
?,
'default', ?);");
$req->execute(array($_SESSION["user_id"], $result["title"], $result["content"]));
All variables are set, I checked that with some echo.
Isn't it possible to "INSERT INTO" a variable ?
(Each user has its own table named by its unique id, that's why I can't directly write the table name in the query)
You can't use a named parameter for a table name; if you want to do that, you'll have to include the name in your SQL directly:
INSERT INTO $tablename (....
However - that's still open to SQL injection attacks.
If you want to store data like that, I'd put everything into a single table, and just add an extra field as an additional key.
No, you can't do this, you need to do like below.
$table = $_SESSION["user_id"];
$req = $db->prepare("INSERT INTO $table (`id`, `parent_id`, `position`, `left`, `right`, `level`, `title`, `type`, `content`) VALUES (NULL, '2', 'last', '3', '10', '2', ?, 'default', ?);");
$req->execute(array($result["title"], $result["content"]));

PHP database getting variables

I have the following line of code that executes properly except for one hitch. It will print the variable name into the database.
I use this code in one of my scrips:
$con = mysql_connect("MyServer","MyDB","myPwd");
mysql_select_db("MyDB", $con);
$sql = "INSERT INTO `MyDB`.`Shipping` (`ID`, `FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `ADDRESS2`, `CITY`, `STATE`, `ZIP`, `ORDERNUMBER`, `SHIPPINGTYPE`, `item1`, `item2`, `item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `item10`) VALUES (NULL, \'$first_name\', \'lname\', \'addr\', \'\', \'city\', \'state\', \'zip\', \'ordernum\', \'\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\', \'0\');";
mysql_query("$sql");
mysql_close($con);
This code prints the followin to the database:
$first_name lname addr city state zip 0 0 0 0 0 0 0 0 0 0 0
Notice that the variable name, and not the contents of the variable are printed. How can I get it to print out the variable contents?
Notice that the variable name, and not the contents of the variable are printed
This is because you are not passing variables to the insert statement, rather you are passing undefined(?) constants; lname, addr, etc. You should pass in the variables you assigned values to: (assuming) $lname, $addr, etc.
Also, you don't need to pass in a NULL for the ID column. If it's set to auto_increment, the database will create this value for you.
You should also take advantage of the default column values defined by your table schema, so you don't end up passing in a huge list of variables with default values, for example, if you have a DEFAULT 0 as part of the schema for item1, item2, item3 etc, you can simply make the following insert:
$sql =
"INSERT INTO `MyDB`.`Shipping` (`FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `CITY`, `STATE`, `ZIP`, `ORDERNUMBER`) VALUES ('$first_name', '$lname', '$addr', '$city', '$state', '$zip', '$ordernum');";
The database will populate item1, item2, etc columns with 0 for you automatically.
As cambraca mentioned, if you pass variables directly into your query like this, you run the risk of SQL injection. You should read up on how to prepare your queries, which will also force you to use mysqli (vs outdated mysql) api. Or even better, read up on PDO.
For one you have a quoting issue. You seem to have double quotes and then escaped single quotes. don't escape your single quotes if you string is double quoted.
It seems the value of $first_name should work. Is this the exact code? Because if you have single quotes around the whole thing it would create the output you're describing.
All your other columns aren't variables so it's hard to know what you're trying to do. If you aren't going to use them why reference them at all?
In your mysql_query call don't quote $sql again.
Finally check mysql_error() for errors. It could be you are seeing something old in the database and your code isn't working at all.
Consider using PDO. It has support for placeholders, better security and better debugging than the native mysql_* interface.
Change the insertion statement to:
$sql = "INSERT INTO `MyDB`.`Shipping`
(`ID`, `FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `ADDRESS2`, `CITY`,
`STATE`, `ZIP`, `ORDERNUMBER`, `SHIPPINGTYPE`, `item1`, `item2`,
`item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `item10`)
VALUES (NULL, '{$first_name}', 'lname', 'addr', '', 'city', 'state',
'zip', 'ordernum', '', '0', '0', '0', '0', '0', '0', '0',
'0', '0', '0');";
Also, do check that your $first_name is properly assigned a value.
I suppose not to use inline variables in strings in PHP, and you are escaping ' when you do not need to. Try this:
$con = mysql_connect("MyServer","MyDB","myPwd");
mysql_select_db("MyDB", $con);
$sql = "INSERT INTO `MyDB`.`Shipping` (`ID`, `FIRSTNAME`, `LASTNAME`, `ADDRESS1`, `ADDRESS2`, `CITY`, `STATE`, `ZIP`, `ORDERNUMBER`, `SHIPPINGTYPE`, `item1`, `item2`, `item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `item10`) VALUES (NULL, '".$first_name."', 'lname', 'addr', '', 'city', 'state', 'zip', 'ordernum', '', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0');";
mysql_query($sql);
mysql_close($con);
Rather than using \'$first_name\' replace it with \"$first_name\" and the same follows with other variables too.

want to do a double MYSQL INSERT INTO to two different tables

I want to be able to insert into two different mysql tables using php with the second mysql insert being dependent on the member id of the first insert.
For example:
mysql_query("
INSERT INTO `member_users` (
`id`,
`first_name`,
`last_name`,
`username`,
`password`,
`address1`,
`address2`,
`postcode`,
`access`,
`expires`
) VALUES (
NULL,
'$fname',
'$lname',
'$email',
'$passhash',
'$add1',
'$city',
'$postcode',
'',
''
)"
);
Then I want to take the id of this member user to create a mysql_query insert on the same page eg:
mysql_query("
INSERT INTO `member_orders` (
`order_id`,
`member_id`,
`date`,
`item`,
`size`,
`quantity`,
`price`,
`tracking_id`,
`status`,
`item_sent`,
`notes`
) VALUES (
NULL,
'$userid',
'',
'',
'',
'',
'',
'',
'',
'',
''
)
");
its probably a really easy answer and a really silly question but cannot seem to find the answer anywhere
thanks in advance
If I have understood correctly, and you need to get the member_id from the first query, to use in the second query, you can use the PHP function
$the_member_id = mysql_insert_id();
http://php.net/manual/en/function.mysql-insert-id.php
You can also do it without using that PHP function
$sql = "SELECT LAST_INSERT_ID()";
// add code here to run the query.
You can use the php function mysql_insert_id() to get the last id you input into the database.
EG:
$sql = "INSERT INTO `table` VALUES (NULL, 'Thomas', 'Male')";
$query = mysql_query($sql);
$id = mysql_insert_id();
So in your question after the first INSERT you need this:
$userid = mysql_insert_id();
Then your second query will work.
You can use mysql_insert_id() to get id, generated by last insert.
mysql_insert_id — Get the ID generated from the previous INSERT operation
You could use the LAST_INSERT_ID MySQL function in your second SQL statement to get the last insert ID from the first.
mysql_query("
INSERT INTO `member_orders` (
`order_id`,
`member_id`,
`date`,
`item`,
`size`,
`quantity`,
`price`,
`tracking_id`,
`status`,
`item_sent`,
`notes`
) VALUES (
NULL,
LAST_INSERT_ID(),
'',
'',
'',
'',
'',
'',
'',
'',
''
)
");
I would recommend that if you use this approach then you execute the queries within a transaction. That way there's no way that another insert can occur between your first insert and your second, thus throwing off the result of LAST_INSERT_ID.
After executing mysql_query() function you can get lastly inserted id of lastly inserted table by mysql_insert_id().
You can do something like what is done in this example
$sql = "INSERT INTO users(name,gender) VALUES ('$name','$gender')";
$result = mysql_query( $sql,$conn );
$user_id = mysql_insert_id( $conn );
$sql = "INSERT INTO website(site,user) VALUES ('$site',$user_id)";
$result = mysql_query( $sql,$conn );
Manual for mysql_insert_id

Categories