PDO looping through and printing fetchAll - php

I'm having trouble getting my data from fetchAll to print selectively.
In normal mysql I do it this way:
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)){
$id = $row['id'];
$n = $row['n'];
$k = $row['k'];
}
In PDO, I'm having trouble. I bound the params, then I'm saving the fetched data into $rs like above, with the purpose of looping through it the same way..
$sth->execute();
$rs = $query->fetchAll();
Now comes the trouble part. What do I do PDO-wise to get something matching the while loop above?! I know I can use print_r() or dump_var, but that's not what I want. I need to do what I used to be able to do with regular mysql, like grabbing $id, $n, $k individually as needed. Is it possible?
Thanks in advance..

It should be
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$n = $row['n'];
$k = $row['k'];
}
If you insist on fetchAll, then
$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
$id = $row['id'];
$n = $row['n'];
$k = $row['k'];
}
PDO::FETCH_ASSOC fetches only column names and omits the numeric index.

Related

Array for a SQL database using PHP

Can someone please help? I'm new to PHP and struggling to make this bit of code to work. For example I have a sql database table with the following schema and data:
Type....rent_price
a..........100
b..........200
c..........300
I want to be able to echo say, "a", in one section and "200" in another. The following code will display "a" but then I can't seem to get it to display anything from the rent_price column using a second array.
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row['type']);
for ($set1 = array (); $row = $result->fetch_assoc(); $set1[] =$row['rent_price']);
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
You loop through the results twice, without resetting. Try to loop only once:
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
$set = array ();
$set1 = array ();
while ($row = $result->fetch_assoc())
{
$set[] = $row['type'];
$set1[] =$row['rent_price'];
}
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
Depending on what you mean by '"a" in one section and "200" in another', you may be able to forgo creating the intermediate arrays and just print the values from your query as you fetch them. Two cells in a table row, for example:
while ($row = $result->fetch_assoc()) {
echo "<tr><td>$row[type]</td><td>$row[rent_price]</td></tr>";
}
your data is in the first element of array
$set1[0]
but youre probably better off maintaining the naming throughout
$results = array();
while ($row = $result->fetch_assoc()){
$results[] = $row;
}
foreach ($results as $result){
echo $result['type'];
echo $result['rent_price'];
}
OR
$results = array();
while ($row = $result->fetch_assoc()){
$results['types'][] = $row['type'];
$results['rent_prices'][] = $row['rent_price'];
}
foreach ($results['types'] as $type){
echo $type;
}
foreach ($results['rent_prices'] as $rent_price){
echo $rent_price;
}

how to view table value without while loop?

while($row = mysql_fetch_assoc($interst_list_select_result))
it's work one value to many value
I need to work without while loop but i need to all value in table.
how to i work this??
You can use a foreach loop.
$stmt = $db->prepare('SELECT * FROM tbl');
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row => $val){
echo $val['colname1'],' ',$val['colname2'];
}
If you need only the first result I think you can do this way
If( $row = mysql_fetch_assoc($interst_list_select_result)){
echo $row['you_column'];
}
if you need all
$rows = $stmt->fetchAll();
foreach ($rows as $row => $index){
echo $index['you_column'];
}

retrieve all datas from selected column and store

$result = mysql_query("SELECT * FROM Race");
$rows = mysql_num_rows($result);
for ($i = 0 ; $i < $rows ; ++$i)
{
$row = mysql_fetch_row($result);
echo $row[0];
}
above is probably an awkward method but it'll print out all datas stored in first column, which is good but now, I want to store each one of them into an array...
I tried
$array[$i]=$row[0];
and echoed it out, but it just prints"Array"...
I tried
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row[0];
}
...which does the same as code written before, i guess, since it too just print "Array".
Please help! Thank you!!
Do you use simple echo $array;? It's wrong. You can't output array this way.
Use this:
$array = array();
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row[0];
}
foreach($item in $array) {
echo $item."<br>"; // and more format
}
If you want to watch array contents without any format use (e.g. for debugging) print_r or var_dump:
print_r($array);
var_dump($array);
Advice: better to use assoc array.
$array = array();
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row['raceid'];
}
Advanced advice: better to use PDO and object results.
You SQL code will be invulnerable to SQL injections
Code will be more modern and readable.

MySQL results issue in php array

Can anybody tell me why not all the results for MySQL aren't ending up in the array?
$result = mysql_query("select * from groups order by id desc");
if ($row = $result->fetch()) {
$groups[] = $row;
}
Use while not if
while ($row = $result->fetch()) {
$groups[] = $row;
}
The code you have there does not iterate over the result set.
Try this instead.
while ($row = $result->fetch()) { 
$groups[] = $row;
}
Because fetch only fetches a row as explained in the php manual:
Fetches the next row from a result set
I'd like to suggest changing your mysql_ code for PDO
$db = new PDO("..."); // Creates the PDO object. Put the right arguments for your connection.
$statement = $db->prepare("SELECT * FROM groups ORDER BY id DESC");
$statement->execute();
while ($groups = $statement->fetch())
{
// Do whatever you want to do
}

How to fetch 2 times in MYSQL PDO without FETCHALL

I have this sample query:
$STH = $DBH->query("SELECT id FROM table");
I want to get the first row and then loop and display all rows. So I use the following to get the first row:
$STH->setFetchMode(PDO::FETCH_ASSOC);
$first_row = $STH->fetch();
$first_row = $first_row['id'];
I use while loop to display all rows again:
while ($list = $STH->fetch()) {
$id = $list['id'];
echo $id;
}
Now the while skips the first row and I want it to be displayed. Is there an equivalent to mysql_data_seek to reset the pointer again to the first row? I know fetchall can be used but it's bad on memory and wasteful. I could also run the query and limit to 1 but this is not recommended as I have a query that joins multiple tables and would be very slow. Is there any other solution?
Thanks
I take that back looks like you can use the cursor orientation contants to select the result... sample code coming... I havent tried this so you may need to play a bit. This is also based on the assumption that a PDO::FETCH_ORI_FIRST acts like a data_seek and leaves the cursor on the first position as opposed to returning it to whatever it was before.
$stmt = $pdo->prepare('SELECT id FROM table', array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$first = $pdo->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_FIRST);
$first_row = $first['id'];
// other stuff
// first iteration we rewind to the first record;
$cursor = PDO::FETCH_ORI_FIRST;
while (false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC, $cursor))) {
$id = $row['id'];
// successive iterations we hit the "next" record
$cursor = PDO::FETCH_ORI_NEXT;
echo $id;
}
I dont think you can rewind a statement... Assuming these blocks arent seprated by a bunch of intermediary logic id just do it in the loop.
$STH->setFetchMode(PDO::FETCH_COLUMN); // no need to pull an array
$count = 0;
while ($id = $STH->fetch()) {
if($count === 0) {
$first_row = $id;
}
echo $id;
$count++;
}
Could you just use a do...while loop instead?
$STH->setFetchMode(PDO::FETCH_ASSOC);
$list = $STH->fetch();
$first_id = $list['id'];
do {
$id = $list['id'];
echo $id;
} while ($list = $STH->fetch());
You can fetch all the result, and then just act on it as an array. So, for instance, you could shift the first result off the front, and then loop over any additional rows:
<?php
$sql = "YOUR QUERY";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// get first row
$firstRow = array_shift($rows);
// loop over remaining rows
foreach ($rows as $row) {
// do something
}

Categories