I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.
I know that I have to use this statement:
LAST_INSERT_ID()
That statement works with a query like this:
$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";
But if I want to get the ID using this statement:
$ID = LAST_INSERT_ID();
I get this error:
Fatal error: Call to undefined function LAST_INSERT_ID()
What am I doing wrong?
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php
Related
I am very confused about this (returning false):
$sql = "SELECT * from tbl_user WHERE group = 'abc'";
$res = mysql_query($sql);
if(mysql_num_rows($res) > 0) {
$response = array('status' => '1');
} else {
$response = array('status' => '0'); // ---> what I get back
die("Query failed");
}
...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group:
$SQL = "SELECT * FROM tbl_user";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['group']; // ---> returns 'abc'
When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing...
This makes me mad. If anyone could help... (I am running a local server with MAMP).
Thanks a lot!
The issue is that group is a reserved word in SQL.
For MySql you need to escape it with backticks
`group`
So your query would be
$sql = "SELECT * from tbl_user WHERE `group` = 'abc'";
After selecting the record with the current KEY and PROGRAM, I want to update the 'log_info' field for that CURRENT record, inputting the date/time. However, I keep getting the 'die error' for the update code.
ERROR CODE:
"Warning: mysql_query() expects parameter 1 to be string"
(for the "$log_info = mysql_query($query,"UPDATE..." code)
Snippet
$query = mysql_query("SELECT *
FROM `product_keys`
WHERE `serial_key` = '".$key."'
AND `program` = '".$prog."' LIMIT 1") or die('error selecting');
// UPDATE 'log_info' value to the latest date and time
$time = time();
$log_time = date('Y-m-d g:i:sa',$time);
$log_info = mysql_query($query,"UPDATE 'product_keys'
SET 'log_info' = '".$log_time."'
WHERE `serial_key` = '".$key."'
AND `program` = '".$prog."' LIMIT 1") or die('log error');
Try this line:
$log_info = mysql_query($query,"UPDATE `product_keys` SET `log_info` = '".$log_time."' WHERE `serial_key` = '".$key."' AND `program` = '".$prog."' LIMIT 1") or die(mysql_error());
Using mysql_error() you can catch specific error of query.
See The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
You have ' around the column name 'log_info' and the table name 'product_keys'. That should be backticks.
update query will be like this
$log_info = mysql_query("UPDATE 'product_keys'
SET 'log_info' = '".$log_time."'
WHERE `serial_key` = '".$key."'
AND `program` = '".$prog."'
LIMIT 1") or die('log error');
because mysql_query function accept 2 Parameters, first Parameter should be sql query , second Parameter is optional that is MySQL connection.
Please i have this quetion,
I have here:
$query = $db->prepare('Update survey_content set '.$type.' = '.$type.'+1 where id = '.$where);
$query->execute();
I'm new to PDO and i really don't know how to create a new query, i need to add a record on the database, is it ok like this?
$query1 = $db->prepare('INSERT INTO daily (selected)
VALUES (.$type.)');
$query1->execute();
Use a placeholder and fill the value in the execute method
$query1 = $db->prepare("INSERT INTO daily (selected)
VALUES (?)");
$query1->execute($selected_data);
or bind the parameter seperately
$query1 = $db->prepare("INSERT INTO daily (selected)
VALUES (:sel_dat)");
$query1->bindParam(":sel_dat",$selected_data);
$query1->execute();
My mysql query is working fine
INSERT INTO donor_location (pc_id)
SELECT id
FROM pc
WHERE postcode= ?
i.e gets the postcode id from a postcode table then inserts that id into donor_location table.
I am using mysqli and prepared statements
without the select part it would be quite easy - something like
$stmt = $mysqli->prepare("INSERT INTO donor_charity(
id) values (?)") ;
however I am completely lost about how to incorporate the select
What you do is almost the same, just changing the query bit.
To select all records from charity_donor where the id is 25, you would do the follwing query:
SELECT *
FROM donor_charity
WHERE id = 25
Now to query this, first you have to prepare it:
$stmt = $mysqli->prepare("
SELECT *
FROM donor_charity
WHERE id = ?
");
Now to loop over the results, you must bind the param, and execute the query.
$stmt->bind_param('d', 25 ); // First param means the type of the value you're
passing. In this example, d for digit.
$stmt->execute();
Then you setup an array to hold the data returned from the query,
$row = array();
stmt_bind_assoc($stmt, $row);
And now to loop over the returned data.
while ( $stmt->fetch () ) {
print_r($row); // Should now contain the column.
}
For documentation, see:
Prepare: http://www.php.net/manual/en/mysqli.prepare.php
Bind param: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Execute: http://www.php.net/manual/en/mysqli-stmt.execute.php
Fetch: http://www.php.net/manual/en/mysqli-stmt.fetch.php
You need to use Bind_param after Prepare statement.
$sql = "INSERT INTO donor_charity(
id) values (?)
";
/* create a prepared statement */
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
/* bind parameters for markers */
$stmt->bind_param('ssssss', $id);
$id = '123456';
/* execute query */
$stmt->execute();
Hope this post helps, it's so simple.
http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertRecordsUsingPreparedStatement.htm
I'm having a problem with running this function. When it runs, it does exactly what I want, except that within my like_requests table the request_id is not the mysql query result linked to the variable $select but Resource Id #22. I thought that resource id's appear when you are trying to echo out a result, but I'm not using echo. What's wrong with the code?
function update_likes($band_requested, $new_likes, $session_user_id) {
$select = mysql_query("SELECT `primary_id` FROM `requests` WHERE
`user_requester_id` = '$session_user_id' AND `person_requested` =
'$band_requested'");
$sql_2 = "INSERT INTO `like_requests` (user_id, request_id) VALUES
('$session_user_id', '$select')";
mysql_query($sql_2);
}
$band_requested = 'rally done';
$new_likes = 239;
$the_session_user_id = 3;
update_likes($band_requested, $new_likes, $the_session_user_id);
UPDATE WITH CORRECTED ANSWER
Here is the code corrected with help from David.
function update_likes($band_requested, $new_likes, $session_user_id)
{
$select = mysql_query("SELECT `primary_id` FROM `requests` WHERE `user_requester_id` =
'$session_user_id' AND `person_requested` = '$band_requested'");
$row = mysql_fetch_row($select);
$request_id = $row[0];
$sql_2 = "INSERT INTO `like_requests` (user_id, request_id) VALUES ('$session_user_id',
'$request_id')";
mysql_query($sql_2);
}
mysql_query returns a resource (http://php.net/manual/en/function.mysql-query.php) not just a scalar value. You'd need to use a function like mysql_fetch_row() to get the, presumably, one row you want, assign that row to a variable $row, then retrieve the primary_id with array syntax like $row['primary_id']. By the way, apparently mysql_query is being eased out and we should use the MySQLi API with the mysqli_query() method.