PHP MySQLi to PDO? - php

I don't know why my code doesn't return true, the while loop works fine, but there's a problem.
$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '?%' ");
$PDO_result->bindParam(1, $pismenka[$i]);
$PDO_result->execute();
Here when I var_dump() $PDO_result I get one item in array so the following while loop should work:
while($row = $PDO_result->fetch(PDO::FETCH_ASSOC))
but it doesn't.
Working MySQLi:
$result = mysqli_query($connect_to_db, "SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '$pismenka[$i]%' ");
while($row = mysqli_fetch_array($result))

The most simple solution would be to change $pdo->fetch(PDO::FETCH_ASSOC) to $pdo->fetchAll(PDO::FETCH_ASSOC)
fetchAll returns ALL rows in the requested query, while fetch only gets 1 row (the first)
Example:
<?php
try {
$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE ?");
//Execute by inserting an array:
if (!$PDO_result->execute([$pismenka[$i] . "%" ])) { //Added ."%"
die('Error!');
}
//Fetch rows:
$rows = $PDO_result->fetchAll(PDO::FETCH_ASSOC);
//Go trough each row:
foreach ($rows as $row) {
//Do something
}
//Catch exceptions thrown by PDO
} catch (PDOException $ex) {
print_r($ex);
}

Related

Foreach implemented on finding array data finds only one data

Ive used two queried in a function. FIrst query to find an array of data. And second query is to select rows as per checking the array data from the first query. But the overall function return only one row data.
function getCartItems($conn)
{
$cust_id=$_SESSION['cust_id'];
$stmtSelect1 = $conn->prepare("SELECT product_id FROM tbl_cart WHERE cust_id=cust_id");
$stmtSelect1->bindParam('cust_id',$cust_id);
$stmtSelect1->execute();
$product_id= $stmtSelect1->fetchAll();
foreach($product_id as $productid) {
$stmtfetch = $conn->prepare("SELECT * FROM tbl_item WHERE product_id=:products_id");
$stmtfetch->bindParam(':products_id',$productid['product_id']);
$stmtfetch->execute();
$datas = $stmtfetch->fetchAll();
print_r($datas);
exit();
}
}
First of all, your code has typos (Missing ":" before parameter, product_id/products_id).
This should work:
$cust_id=$_SESSION['cust_id'];
$stmt = $conn->prepare("SELECT tbl_item.* FROM tbl_cart, tbl_item WHERE tbl_cart.cust_id = :cust_id AND tbl_item.product_id = tbl_cart.product_id);
$stmt->bindParam('cust_id',$cust_id);
$stmt->execute();
$rows = $stmt->fetchAll();
foreach($rows as $row)
{
print_r($row);
}

Query returning just one row

I'm running this MySQL query in PHP:
SELECT * FROM settings
This is the settings table:
id ------- name ------- value
_____________________________
1 --------- one --------- 1
2 --------- two --------- 2
For some reason, when I run my query I'm only given the first result (even when running a foreach loop).
I've taken a look around and can see that a workaround is to run a while loop. This to me looks a bit counter-active.
My question is, why is this occurring, and how can I fix it to run as a standard foreach loop?
Edit
The PHP code:
$query = #mysql_query("SELECT * FROM settings");
$result = mysql_fetch_assoc($query);
print_r($result);
you have to walk through you resultset with a loop:
$con=mysqli_connect("localhost","username","password","database");
$query = "SELECT * FROM settings";
$result = mysqli_query($con, $query);
echo "<pre>";
while ($row = mysqli_fetch_assoc($result)) {
print_r($row);
}
or if you want to use PDO (i.e. use a foreach):
try {
$db = new PDO("mysql:dbname=databasename;host=localhost", "username", "password" );
$sql = "SELECT * FROM settings";
foreach ($db->query($sql) as $row) {
print_r($row);
}
} catch(PDOException $e) {
echo $e->getMessage();
}

Create an array from database results

I want to create an array from a database query. I want to select 10 random questions by their ID, and put them into an Array, JUST the ID, i do not want it to be like [0]=>array('1'),[1]=>array('2'), I would like to to simply be, array('1','2','3') etc.
After they are in the array i would like to be able to check if the id is in the array
If u use the PDO php extension, use the http://www.php.net/manual/en/pdostatement.fetchcolumn.php to retrieve the values of the column as one-dim array.
try {
$pdo = new PDO([dsn], [username], [password]);
$sql = "
SELECT ID
FROM [tablename]
ORDER BY RAND()
LIMIT 10
";
$statement = $pdo->prepare($sql);
if (!$statement) {
//error handling here
}
$result = $statement->execute();
if (!$result) {
//error handling here
$array = array();
while (list($id) = $statement->fetch(PDO::FETCH_NUM)) {
$array[] = $id;
}
$statement = NULL;
} catch (PDOException $e) {
//error handling here
}
This should leave an enumerated array of the ID's

Alternative to fetchall (PDO)?

What is alternative to fetchall for real time loop?
Consider this:
$query = $db->prepare("SELECT * FROM record WHERE status = 0");
$query->execute();
$Record = $query->fetchall(PDO::FETCH_ASSOC);
foreach ($Record as $row) {
echo $row['name'];
sleep(5)
}
While its looping and echo'ing, I updated status = 1 from the console but it will still show the record which it shouldn't.
How about a simple fetch(): http://us3.php.net/manual/en/pdostatement.fetch.php
$query = $db->prepare("SELECT * FROM record WHERE status = 0");
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'];
sleep(5)
}
The results of the query are calculated once, when you run the query. If you need to get all new results with status = 0, you'll need to rerun the query.

PDO: Does fetchColumn moves the pointer of the returned results set?

I recently implemented PDO and noticed that my query results lacked the first row. That's probably because fetchColumn() retrieves the first row and moves the pointer to the second row so that the while() loop starts at row 2. Is that correct? If so, how can I avoid that and improve the following code block?
$STH = $DBH->prepare("SELECT * FROM users");
$result = $STH->execute();
if (!$result)
{
return false;
}
elseif($STH->fetchColumn()>0)//counterpart of mysql_num_rows()
{
while ($row = $STH->fetch())
{
...
}
}
}
Is that correct?
Yes. Also, fetchColumn() is not an equivalent for mysql_num_rows(). Instead, fetchColumn() retrieves the indexed column value (defaulting to index 0) of the current row and as assumed, advances the cursor.
If you need a count of the number of rows returned in your query, I suggest you first issue a SELECT COUNT(1) ... query with the same conditions, using fetchColumn() to return the count.
See example #2 on this manual page - http://www.php.net/manual/en/pdostatement.rowcount.php
For example
$stmt = $DBH->query('SELECT COUNT(1) FROM users');
// using a straight PDO::query() call as a prepared statement would be
// overkill for these queries
if ($stmt->fetchColumn() == 0) {
return false;
}
$stmt = $DBH->query('SELECT * FROM users');
while ($row = $stmt->fetch()) {
...
}
After googling around I came up with this solution:
$STH = $DBH->prepare("SELECT * FROM users");
if(!$STH)
{
$error = $DBH->errorInfo();
}
else
{
$result = $STH->execute();
if($result===false)
{
return false;
}
else
{
$rows = $STH->fetchAll(PDO::FETCH_ASSOC);
if(count($rows) > 0)
{
foreach ($rows as $row)
{
...
}
}
}
}
}

Categories