This question already has answers here:
PDO get the last ID inserted
(3 answers)
Closed 5 years ago.
I am trying to get the last id number of Database. But It's showing only 0.
I am learning PDO. Can anyone tell me how can I do it?
if($_SERVER['REQUEST_METHOD']=='POST'){
$sql = "SELECT * FROM tablename";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt ->fetch();
$showid = $pdo->lastInsertId();
echo $showid;
}
lastInsertId will return the ID of a row that was inserted by the same connection. You can't use it outside of that context.
The easiest way to fetch the last ID would be to run something like,
SELECT max(id) FROM tablename
If you're using this in order to work out which ID should be inserted next, consider using an auto-increment column for your ID instead.
lastInsertId() works only after a INSERT query - since you're only doing a select, it will always return string(1) = 0
So either you perform this code after an INSERT statement, or you can do the following:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
Refering here to: PDO get the last ID inserted
Visit this thread, you'll find my samplecode provided by Corbin and much more informations on this topic.
Related
This question already has an answer here:
Trying to access array offset on value of type bool
(1 answer)
Closed 1 year ago.
I am trying to have a display (Completed Repairs = ?) on my admin dashboard that displays the number of laptop repairs completed based on the status column.
<?php
$pdo = new PDO(
'mysql:host=127.0.0.1;dbname=MYAPP',
'MYUSERNAME',
'MYPASSWORD'
);
//The COUNT SQL statement that we will use.
$sql = "SELECT COUNT(*) FROM repairs WHERE current_status > Repair Completed";
//Prepare the COUNT SQL statement.
$stmt = $pdo->prepare($sql);
//Execute the COUNT statement.
$stmt->execute();
//Fetch the row that MySQL returned.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//The $row array will contain "num". Print it out.
echo $row['num'];
?>
But i am getting this error: Notice: Trying to access array offset on value of type bool in PATH_TO_PHP_FILE.php on line 208
Line 208 is:
echo $row['num'];
I am a complete newby so i have no idea what to do here.
I am using "num" cause i want to get the number of rows that have a status of "Repair Completed".
I have looked around on stackoverflow but i am not really understanding any of it.
What am i missing from my code? Any help will be greatly appreciated.
Your sql request seems wrong so it returns false try
$sql = "SELECT COUNT(*) FROM repairs WHERE current_status = 'Repair Completed'"
And after that do a var_dump of $row
This question already has answers here:
How to insert values in a PHP array to a MySQL table?
(2 answers)
Closed 5 years ago.
I'm using PHP session variable to track character ID's between two tables, characters and character_data_store.
The session ID definitely has the correct ID as I have had to print its value before it goes into the mySQL query.
For testing I selected a user I knew had a rapsheet and used
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.`key` = 'RapSheet'
AND character_data_store.character_id = '216'";
Obviously I can't use this for all users as I need to confirm the right one has been selected so thats where the session variable comes in.
I've tried using:
$correctPlayer = $_SESSION['selpid'];
echo $correctPlayer; #confirm it's the right id and then remove
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = '$correctPlayer'";
I did some searching on SO and I found that int's need to have double quotes around them not single quotes, I tried that and had no luck but someone else suggested putting the session ID in exactly which I tried next:
$usersql = "SELECT *
FROM character_data_store
WHERE character_data_store.'key' = 'RapSheet'
AND character_data_store.character_id = {$_SESSION['selpid']}";
Each time I do this I get mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given which SO tells me is because this operation results to false, I assume because it's not accepting the playerID from selpid or $correctPlayer?
It definitely works with the testing user where the playerID is inserted directly into the query. But I can't think of a way to do that since I need to match the playerID from table "characters" where the search is done against their first and last name and then pull the rapsheet data against the same playerID in table "character_data_store".
How do I use a variable in the WHERE condition of a MySQL query using a php variable?
You have obvious error in your code. You are missing quotes in {$_SESSION['selpid']} and you are using quotes in column name. Your query should be
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.`key` = 'RapSheet' AND character_data_store.character_id = '{$_SESSION['selpid']}'";
You should not use quotes in column name, instead use backquotes(`) if you really need. I recommend prepared statements.
There are multiple ways to do this. A naive way to do this would be-
$usersql = "SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ".$correctPlayer;
But to avoid sql injections I would recommend you use bindparam function to bind paramaters in a statement.
$sql="SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ?";
if($stmt = $dbh->prepare($sql)){
$stmt->bindParam(1, $correctPlayer, PDO::PARAM_STR);
$ql = $stmt->execute() or die("ERROR: " . implode(":", $dbh->errorInfo()));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result['data'] = $row;
This question already has an answer here:
Simplest method to retrieve single (and only) row in SQLite using PDO
(1 answer)
Closed 6 years ago.
I am using PDO+Mysql where I am passing udid from a session and if the rowcount is greater than 0, I would like to fetch id from the table as well as first_name, which is the fifth column in the table.
The problem is id is always returned right but not the first_name, not sure why
$stmt = $con->prepare("SELECT * FROM members WHERE id= :udid");
$stmt->bindValue(':udid', $_SESSION['udid']);
$stmt->execute();
$id=$stmt->fetchColumn();
$first_name=$stmt->fetchColumn(5);
I think you can use fetch() to fetch the entire row and then call each column by its name
$stmt->execute();
$result = $stmt->fetch();
$id = $result['id'];
$name = $result['name'];
//and so on for all the columns
This question already has answers here:
Row count with PDO
(21 answers)
Closed 6 years ago.
I have a SELECT query, like this:
$stmnt = $conn->prepare("SELECT post_title, posts_cat FROM posts WHERE posts_cat=:posts_cat");
$stmnt->execute(array(':posts_cat' => $cat_id));
$post_info = $stmnt->fetch();
$count = $stmnt->rowCount();
If there are no posts it shows none, but if there's one or more then it displays only one.
Can someone tell me why this is?
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
rowCount() is not for a SELECT query, use a separate COUNT query for that or fetch all rows in an array and count its size
Please do not use rowCount() with select query
use a different query with count() for counting rows
$sql = "SELECT count(*) FROM `posts` WHERE posts_cat = :posts_cat";
$stmnt = $conn->prepare($sql);
$stmnt->execute(array(':posts_cat' => $cat_id));
$count = $stmnt->fetchColumn();
Of course you are getting the right number of rows returned. 1 means that only one row was found. If you want more rows to be found, add more rows to your database to match the condition.
Whether you need such a function at all - is another question, already answered in this post
This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 9 years ago.
I want to fetch results from a MySQL database with PDO. The user should be able to order them by tablerow by which type (ascending or descending). This seems to only work when you hardcode it.
Does work:
$query = "SELECT * FROM ".$config->dbPrefix."content
WHERE cat_id = 2
ORDER BY id DESC
";
$query = $pdo->prepare($query);
$query->execute();
$result = $query->fetchAll();
Doesn't work:
$orderRow = 'id'; //from $_POST
$orderType = 'DESC' //from $_POST
$query = "SELECT * FROM ".$config->dbPrefix."content
WHERE cat_id = 2
ORDER BY :orderRow :orderType
";
$query = $pdo->prepare($query);
$query->bindValue(':orderRow', $orderRow);
$query->bindValue(':orderType', $orderType);
$query->execute();
$result = $query->fetchAll();
So my question is: what is the best way to do this and why isn't this implemented?
The best way I can think of is using a switch statement and writing the query for every different option which would have like 14 different available cases.
You can only provide placeholders for values in an SQL statement, not for column names or other kind of identifiers.
So instead of using bindValue, put the values in like you do for #config->dbPrefix, directly into the string. Make sure however that no SQL injection is possible.