PDO query not executing in while loop - php

I am tyring to use PDO to retrieve data from a database.
I can retrieve 'NAME' during the first iteration but not after the 2nd iteration.
my code is as follows:-
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row["ID"];
$query = "SELECT NAME FROM Style_Master WHERE ID=$id";
$stmt = $db->query($query);
$style_name = $stmt->fetch(PDO::FETCH_ASSOC)["NAME"];
echo $style_name; // for first id name is displayed but for next id onwards no style name is displayed.
}

$stmt->fetch(PDO::FETCH_ASSOC)["NAME"]; ?
$style_name = $stmt2->fetch(PDO::FETCH_ASSOC)["NAME"];

I'm supposing that you have a piece of code like this
$queryA = "SELECT id, somethingelse FROM somewhere";
$stmt = $db->query($queryA);
Before the while loop.
At first iteration you fetch the first record resulting from queryA
After you re-assign the same variable $stmt with other records coming from
$query = "SELECT NAME FROM Style_Master WHERE ID=$id";
It happens that at second iteration (assuming there are many NAMEs with same ID otherwise the loop ends), you look for a field "id" into the result-set of query you used to find "name".
So you iterate the query using id=null

The problem with your code is related with the variable scope.
When you do something like this: (see the comments)
<?php
$stmt = 10;
while (0 < $stmt){
// here, I am acessing the outside varialbe $stmt
echo "{$stmt}<br>"; // 10 will be printed
$stmt = 0; // I am modifying the outside variable.
$stmt--; here the outside variable will be -1
echo "{$stmt}<br>"; // will print -1. And loop will end
}
With this, your code should be like this:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row["ID"];
$query = "SELECT NAME FROM Style_Master WHERE ID=$id";
$stmt2 = $db->query($query);
$style_name = $stmt2->fetch(PDO::FETCH_ASSOC)["NAME"];
echo $style_name; // for first id name is displayed but for next id onwards no style name is displayed.
}
This:
$stmt2 = $db->query($query);
Because the outside variable $stmt should not be modified inside your loop.
When you do :
$stmt = $db->query($query);
You are modifying the outside variable and with that, you are changing your loop behavior.

Related

What is wrong with this php while loop which keeps the page from loading?

I am trying to use a while loop to echo out all the student id's that belong to one account number. While the given below code executes fine when I remove the while loop, it gives no output with the while loop, and the browser page keeps loading. Here is the code:
include "database.php";
$q = $_REQUEST["student_id"];
$q = strtolower($q);
$trimmed = trim($q);
$query4 = "select student_id from acc_details where account_no= (select account_no from acc_details where student_id = $trimmed)";
while ( $arr1 = mysqli_fetch_assoc(mysqli_query($con, $query4))) {
extract($arr1);
echo "<h1> $student_id </h1>";
// I want to echo out some html output here
}
Problem:
it gives no output with the while loop, and the browser page keeps loading.
Solution:
Look at the following statement carefully,
while ( $arr1 = mysqli_fetch_assoc(mysqli_query($con, $query4))) {
...
}
The problem is, in each iteration of while loop you're executing your query, and that's why while loop keep on executing, it never ends. Execute your query outside of while loop and take the result set to loop through it, like this:
include "database.php";
$q = $_REQUEST["student_id"];
$q = strtolower($q);
$trimmed = trim($q);
$query4 = "select student_id from acc_details where account_no IN (select account_no from acc_details where student_id = {$trimmed})";
$result=mysqli_query($con,$query4);
while ($row = mysqli_fetch_assoc($result)) {
// your code
}

printing the value of a query using php

I'm trying to print out the value of a query but what appears on the screen is the query itself!
mysql_select_db($database_databasestudents, $databasestudents);
$result = mysql_query("Select name from country where id = '$s';",$databasestudents);
$r = mysql_fetch_array($result) ;
echo $r;
where $s is an integer
This is what I get on the screen:
SELECT name FROM country WHERE id='3'
3 is the value of $s
You need to run the query first
http://www.php.net/manual/en/mysqli.query.php
and then loop though the results
http://www.php.net/manual/en/mysqli-result.fetch-array.php
You need to run the query in order to get the result. Maybe this will get you started:
$pdo = new PDO('mysql:host=YOURHOST;port=YOURPORT;dbname=YOURDB', 'YOURUSER', 'YOURPASSWORD');
$sql = 'SELECT name FROM `country` WHERE id=?';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($s));
while ($result = $stmt->fetchObject())
{
echo $result->name;
}
$r is an array, not a string. You need print_r($r); or var_dump($r);, not echo
You have created a string containing your query.
You must instantiate a database connection and then execute your query.

Retrive an array stored in database using PDO

I have an array: productid = [1,2]. Now I want to fetch data from product table by using this part of code:
$sql = 'SELECT name FROM product WHERE id=:id';
$s = $pdo->prepare($sql);
foreach($productid as $id)
{
$s->bindValue(':id', $id);
$s->execute();
}
when I returned the names as follow:
foreach($s as $row)
{
$name[] = array(
'name' => $row['name']
);
}
I just got the product name of second id and didn't get both names.
What's the problem?
I just got the product name of second id and didn't get both names. What's the problem?
You've got to put your $name[] = $row['name']; (yes, that's right notation) code inside of the foreach loop, as well as code that actually fetches the data.
You may also form a IN() statement that should be looks like IN (?,?,?,?) and run it in one query. Something like this (not tested):
$in = trim(str_repeat('?,',count($productid)).",");
$sql = "SELECT name FROM product WHERE id IN ($id)";
$stmt = $db->prepare($sql);
$stmt->execute($productid);
$name = $stmt->fetchAll();

Mysqli fetch array nth row

I have the following code that fetches a single row:
$query = "SELECT *
FROM translations
WHERE iddoc = '$id'
AND submitted = 1;";
$result = mysqli_query($query);
$row = mysqli_fetch_array($result);
I know this is useful in a while loop, where you can just loop through the results.
But I need to be able to grab specific rows that meet this condition. Something following this pseudo code:
$query = "SELECT *
FROM translations
WHERE iddoc = '$id'
AND submitted = 1;";
$result = mysqli_query($query);
$arrayofrows = mysqli_fetch_arrayofrows($result);
$arrayofrows[0] //(to get the first row)
$arrayofrows[1] //(2nd row)
and so on...
How can I do this?
You can try something like this
$arrayofrows = array();
while($row = mysqli_fetch_array($result))
{
$arrayofrows = $row;
}
You can now have
$arrayofrows[0] //(to get the first row)
$arrayofrows[1] //(2nd row)
I think the function you are looking for is mysqli_fetch_all as shown below. This avoids the need to create an extra looping structure or a function to do something already provided.
$query = "SELECT *
FROM translations
WHERE iddoc = '$id'
AND submitted = 1;";
$result = mysqli_query($query);
$arrayofrows = mysqli_fetch_all($result);
$arrayofrows[0] //(to get the first row)
$arrayofrows[1] //(2nd row)
It depends on whether you require the entire result set back or not but I think the LIMIT could be used like:
$query = "SELECT *
FROM translations
WHERE iddoc = '$id'
AND submitted = 1 LIMIT 200,200;";
Otherwise as others say you will need to convert to an array (which is what fetch_all does) and then get the element from that array.

PHP Zend - Execute to get a rowset and total number of records

I encounter some problem where i want to execute a SQL statement and get the total number of records + all the records.
$strSQL = "SELECT * FROM table WHERE ProjectID = 1 ";
$stmt = $db->query($strSQL);
$total = count($stmt->fetchAll());
while ($row = $stmt->fetch()){
..No More Record Shown here..
}
but there is no more record in the while loop after i execute fetchAll, i believe I need to get back to the first row or something, anyone know how to fix this?
You've already fetched all the records with fetchAll(). So when you call fetch(), there are no more records to read. Try storing the return value of fetchAll() in a variable and iterating through that. Something like this:
$strSQL = "SELECT * FROM table WHERE ProjectID = 1";
$stmt = $db->query($strSQL);
$allRows = $stmt->fetchAll();
$total = count($allRows);
foreach ($allRows as $row){
// process each $row
}

Categories