How to check EXISTS result - PDO - php

I use a http://php.net/ page code for conecting with PDO. I Add the EXIST term. How to check if the EXISTS return false? If is not posible, how to check if select return an empty result?
try {
$conn = new PDO("mysql:host=$servername;dbname=xxxx", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
getUsers($conn,$po[0]);
$conn = null;
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
function getUsers($con,$po){
$sql = "SELECT * FROM usuarios WHERE EXISTS (SELECT id FROM webs WHERE name='$po')";
foreach ($con->query($sql) as $row) {
print $row['nombre'] . "\n";
print $row['id'] . "\n";
print $row['email'] . "\n";
}
}

The WHERE EXISTS returns a standard SELECT result (rows) based on the subquery after key EXISTS
So, to check if the EXISTS fails, you have to use rowCount, that return the number of rows returned by the query:
$result = $con->query($sql);
if( $result->rowCount() > 0 ) echo "EXISTS";
else echo "NOT EXISTS";
(Edit:)
Please note:
As noted in the comments below, the rowCount() works fine in this case and always with mySQL database structures, but «this behaviour is not guaranteed for all database» structures: with sqLite, i.e., it doesn't works.

if you will use like this then it will work and no require for check condition
$rows = $con->query($sql);
if($rows){
foreach ($rows as $row) {
print $row['nombre'] . "\n";
print $row['id'] . "\n";
print $row['email'] . "\n";
}
}

Related

How to display a unsorted list using PDO on SQLite table?

I try to display a results of a SELECT query using PDO in a unsorted list and for that I use this code:
<?php
try {
$conn = new PDO('sqlite:db/MyDatabase.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT genus, species FROM MyTable ORDER BY genus ASC, species ASC");
$stmt->execute();
$data = $stmt->fetchColumn();
echo '<ul>' . '<li>' . $data . '<br/>' . '</li>' . '</ul>';
}
catch(PDOException $e) {echo "Error: " . $e->getMessage();}
$conn = null;
?>
But I only get displayed the first item of the column "genus".
How can I get a unsorted list in a more friendlier form of "genus (space) species"?
fetchColumn() only returns the first column from a result set fetchAll() will return all rows from a table. Then loop through the array using foreach or while.
Trying to echo $data will not work since you cannot echo an array, you would need to specify the array keys which in this case would be the column names.
<?php
try {
$conn = new PDO('sqlite:db/MyDatabase.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT genus, species FROM MyTable ORDER BY genus ASC, species ASC");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<ul>';
if ( !empty($data) ) {
foreach ( $data as $row ){
echo '<li>'. $row['genus'] .' '. $row['species'] .'</li>';
}
} else {
// something to show when no results.
}
echo '</ul>';
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

my pdo connection doesn't work

Echoing to my previous question about SQL-injection. I'm trying to set up a PDO connection.
For that I want to replace my old code with the new:
Here is the old
$conn = mysql_connect("localhost", "sec", "dubbelgeheim") or
die('Error: ' . mysql_error());
mysql_select_db("bookshop");
$SQL = "select * from productcomment where ProductId='" . $input . "'";
$result = mysql_query($SQL) or die('Error: ' . mysql_error());
$row = mysql_fetch_array($result);
if ($row['ProductId']) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
} else
echo "No Record!";
mysql_free_result($result);
mysql_close();
And here is the new:
$input = $_GET['input'];
if ($input) {
$user= 'sec';
$pass = 'dubbelgeheim';
try {
$dbConn = new PDO('mysql:host=127.0.0.1;dbname=bookshop', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$escaper = $db->real_escape_string($input);
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $escaper);
$statement->execute();
$result = $statement->get_result();
$statement->close();
$count = $result->num_rows;
if ($count > 0) {
while ($row = $result->fetch_assoc()) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
}
}
else {
echo 'No record!';
}
$result->free();
$db->close();
}
When I tried this new code.. It gives the following error:
Error!: SQLSTATE[HY000] [1045] Access denied for user
'sec'#'localhost' (using password: YES)
I also tried to replace localhost with 127.0.0.1.
My goal is to make my page secure for SQL-injection.
May anyone have a great solution!
The code looks ok at first glance.
Try this solution. It looks like this anonymus user might be the problem.
EDIT: (as suggedted in comments)
In summary:
The recommended solution is to drop this anonymous user. By executing
DROP USER ''#'localhost';

Need help fetching an array from a prepared statment

I am new to using prepared statement with PHP. I am trying to get the value of "full_name"... So far I am stuck over here. Can anyone please help figure this out? Thanks!
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT * FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$row = $stmnt->fetch();
You need to use bind_result to bind variables to the columns you want. Then each time you call fetch(), those variables will be updated with the next row's values. fetch() with mysqli does not return you the row/result.
This means you cannot use SELECT *. You need to specify which fields you want.
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT full_name FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$stmnt->bind_result($full_name);
$stmnt->fetch();
echo $full_name;
Or, if you have the mysqlnd driver installed, you can use get_result() to get a result set just like if you had ran a normal query, not a prepared statement.
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT * FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$result = $stmnt->get_result();
$row = $result->fetch_assoc();
echo $row['full_name'];

PHP PDO with foreach and fetch

The following code:
<?php
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
echo "Connection is successful!<br/>";
$sql = "SELECT * FROM users";
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
$dbh = null;
}
catch (PDOexception $e) {
echo "Error is: " . $e-> etmessage();
}
Output:
Connection is successful!
person A-male
person B-female
Running "foreach" twice is not my purpose, I'm just curious why TWO "foreach" statements only output the result once?
Following is the similar case:
<?php
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
echo "Connection is successful!<br/>";
$sql = "SELECT * FROM users";
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
$dbh = null;
}
catch (PDOexception $e) {
echo "Error is: " . $e-> etmessage();
}
Output:
Connection is successful!
person A-male
person B-female
SCREAM: Error suppression ignored for
Warning: Invalid argument supplied for foreach()
But when I delete the first "foreach" from the above codes, the output will become normal:
<?php
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
echo "Connection is successful!<br/>";
$sql = "SELECT * FROM users";
$users = $dbh->query($sql);
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
$dbh = null;
}
catch (PDOexception $e) {
echo "Error is: " . $e-> etmessage();
}
Output:
Connection is successful!
user_id-0000000001
name-person A
sex-male
Why does this happen?
A PDOStatement (which you have in $users) is a forward-cursor. That means, once consumed (the first foreach iteration), it won't rewind to the beginning of the resultset.
You can close the cursor after the foreach and execute the statement again:
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . " - " . $row["sex"] . "<br/>";
}
$users->execute();
foreach ($users as $row) {
print $row["name"] . " - " . $row["sex"] . "<br/>";
}
Or you could cache using tailored CachingIterator with a fullcache:
$users = $dbh->query($sql);
$usersCached = new CachedPDOStatement($users);
foreach ($usersCached as $row) {
print $row["name"] . " - " . $row["sex"] . "<br/>";
}
foreach ($usersCached as $row) {
print $row["name"] . " - " . $row["sex"] . "<br/>";
}
You find the CachedPDOStatement class as a gist. The caching iterator is probably more sane than storing the result set into an array because it still offers all properties and methods of the PDOStatement object it has wrapped.
Executing the same query again only to get the results you already had, as suggested in the accepted answer, is a madness. Adding some extra code to perform such a simple task also makes no sense. I have no idea why people would devise such complex and inefficient methods to complicate such primitive, most basic actions.
PDOStatement is not an array. Using foreach over a statement is just a syntax sugar that internally uses the familiar one-way while loop. If you want to loop over your data more than once, simply select it as a regular array first
$sql = "SELECT * FROM users";
$stm = $dbh->query($sql);
// here you go:
$users = $stm->fetchAll();
and then use this array as many times as you need:
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Also quit that try..catch thing. Don't use it, but set the proper error reporting for PHP and PDO
This is because you are reading a cursor, not an array. This means that you are reading sequentially through the results and when you get to the end you would need to reset the cursor to the beginning of the results to read them again.
If you did want to read over the results multiple times, you could use fetchAll to read the results into a true array and then it would work as you are expecting.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Here $users is a PDOStatement object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach is essentially shorthand for:
while ($row = $users->fetch()) ...
Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
Here all results are being output by the first loop. The call to fetch will return false, since you have already exhausted the result set (see above), so you get an error trying to loop over false.
In the last example you are simply fetching the first result row and are looping over it.
$row = $db->getAllRecords(DB_TBLPREFIX . '_payplans', '*', ' AND ppid = "' . $myid . '"');
foreach ($row as $value) {
$bpprow = array_merge($bpprow, $value);
}
This is based on PHP functions where you can globally use this data.

PDO row count confusion

I am making a login page that checks for matching values in a database if the SELECT query returns a matching row with username and password then it will return a row count of 1. The way I have it coded right now when I echo the variable that stores the row count it will echo 26 for some reason and I'm not to sure why.
Would someone explain if I am doing something wrong or if this is normal behavior and where that value is coming from?
function checkLogin($conn,$myusername,$mypassword,$row,$row1){
try {
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
if($results->fetchColumn() > 0) {
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
$rowCount = count($row);
echo $rowCount;
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
echo $count;
}
else {
print "NO ROWS";
}
}
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
Your code, $rowCount = count($row);, is counting the columns in the current row - not the number of rows returned by the query.
On the same note, you are echoing a second count related variable, $count, but you neither declare-it nor increment it in your code. It looks like this one is the one that's supposed to be counting the number of rows you loop through. If this is true, you should set it as $count = 0; before the loop and use $count++; within it:
$count = 0;
foreach ($conn->query($sql) as $row) {
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
$count++;
}
echo $count;
Also, you're currently using PDO's rowCount prior to selecting a user, and you're using it properly. You could just store that result into a variable and use it to tell how many rows you are receiving:
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
$numRows = $results->fetchColumn();
if($numRows > 0) {
... rest of your code ....
function checkLogin($conn,$myusername,$mypassword,$row,$row1)
{
try
{
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql))
{
$count = $results->fetchColumn();
echo "$count\n";
if($count > 0)
{
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
}
else
{
print "NO ROWS";
}
}
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}

Categories