Convert Mysql select query loop for values into PDO loop - php

I have been doing MYSQL just fine for a while now but am trying to learn how to do all that i know with PDO; what I am struggling with now is a simple SQL select, and then I loop through all the rows and dump the corresponding column values into a variable; and then I can do something with the variables for that row while in the loop; here is the way I used to do it with mysql:
$result42 = mysql_query("SELECT * FROM members");
while($row = mysql_fetch_array($result42, MYSQL_BOTH))
{
$user_id=$row['user_id'];
$user_name=$row['user_name'];
$email=$row['email'];
// do something with info for each user; like maybe echo their info...
}
I am attempting to do the same thing with PDO but not finding anything quite like what I am trying to do…
I found some code which uses fetchall and fetchassoc and seems to be putting it in an array; but I have no idea how to loop through the array and get each value on the row like i did with mysql above; and I am not even sure if the PDO that i have here can do that…
this is what I have:
$stmt = $dbh->prepare("SELECT * FROM members");
$products = array();
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$products[] = $row;
}
}
All i want to do is end up cycling through each row getting the values, doing something with them and then moving on to the next row…
Can anyone help with this? Thanks...

Related

Select statement fill data in a foreach

I'm trying to create a php file that when clicking a 'Edit' Link it will get that job ID and list the number of rows by jobRef in my applications table.
This is just to list all of the applications for the different jobs i have available on my website.
<?php
require 'mysqlcon.php';
if(isset($_GET['id']))
{
$stmt = $pdo->query('SELECT FROM applications WHERE applicationID = :id');
$results = $stmt->fetchAll();
echo "<table><tr><td>Job Reference</td><td>Job Title</td><td>Job Location</td><td>Job Description</td><td>Salary</td><td>Availability</td> <td>Category</td><td>Apply</td>";
foreach ($results as $row) {
echo "<tr><td>".$row['applicationID']."</td>". "<td>".$row['jobRef']."</td>", "<td>".$row['fName']."</td>", "<td>".$row['lName']."</td>";
}
}
?>
My error is that i cannot get my code to work; I've tried using "PDO::FETCH_ASSOC" but still no help.
Any ideas on where i've gone wrong?
You need to use prepare and execute, for binding/parameterized queries. You also need to pass the value to the query. Try this:
$stmt = $pdo->prepare('SELECT * FROM applications WHERE applicationID = ?');
$stmt->execute(array($_GET['id']));
$results = $stmt->fetchAll();
Your select query also needs the value that your are selecting. I've put in * which is every column. If you only want some columns list them separated by commas.
The concatenation and comma separation in your echo is strange but I think should work..
Final note, your table doesn't close; you should add a </table> after the foreach.
Final additional note for errors use, http://php.net/manual/en/pdo.errorinfo.php.

Php array from mysql column

I looked at this question:
Create PHP array from MySQL column
and what seems to work for everyone is this:
$array= array();
while ($row = mysql_fetch_array(mysql_query("SELECT Username FROM inloggen"))) {
$array[] = $row['Username'];
}
But when I run this code it infinitely adds the first username in my database to the array.
Does anyone know what I'm doing wrong?
You're re-executing the query endlessly, because you're doing it as part of your while, so if any records are returned , your code will re-query and return the same result time and again
Execute the query, then iterate over the result set
$result = mysql_query("SELECT Username FROM inloggen");
$array = array();
while ($row = mysql_fetch_array($result)) {
$array[] = $row['Username'];
}
Caveat: The MySQL extension is a deprecated interface; you should be using MySQLi or PDO

Quicker way of doing this

I'm using PDO to get an array of relations from my DB.
$dbRelaties = $dbh->query("SELECT pkRelatieId,naam,email FROM relaties");
in another function i need to acces one specific row in this array. I've managed to do it like this:
$klant = array();
foreach($dbRelaties as $dbRelatie)
{
if($dbRelatie["pkRelatieId"] == $relatie){ $klant = $dbRelatie; break; }
}
sendMail("Subject",$klant);
The above code works. But i'me looking for a neater solution and a quicker one, the above code is called in a function and that function is called inside a loop. So everytime it executes is has to loop through $dbRelaties to get the correct relation.
Can anyone set me in the right direction?
assuming the pk means primary key, then
while($row = mysql_fetch_assoc($result)) {
$dbRelatie[$row['pkRelatieID']] = $row;
}
would produce an array keyed with your primary key field, so
$dbRelatie[$pk]['naam']
will give you that particular pk's naam value.
To show a PDO specific version of Marc B's answer.
Assuming a query was executed through PDO like so:
$sql = "SELECT pkRelatieId,naam,email FROM relaties";
$resultSet = $pdo->query($sql);
The results can be read into a PHP array using PDO's fetch method.
$dbRelaties = array();
while ($row = $resultSet->fetch(PDO::FETCH_ASSOC)) {
$dbRelaties[$row['pkRelatieID']] = $row;
}
This can then be used to access values based on the PK of the row.
sendMail("Subject", $dbRelaties[$relatie]['naam']);
Furthermore. PDO lets you assign a default fetch mode to each PDO instance, and the PDOStatement class is Traversable, so that you don't actually have to call the fetch() method in a while loop to go through a result set.
If you were to do this to a PDO object before a query: (Ideally only once right after creating the object.)
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
Then you can use a foreach loop on the result set to get row arrays with field names, instead of using a while loop.
$dbRelaties = array();
foreach ($stmt as $row) {
$dbRelaties[$row['pkRelatieID']] = $row;
}

How to perform a function for every row in a mysql array?

UPDATE: I solved it using a for loop:
for ($i=0; $i < mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);
echo $row['name'];
}
ORIGINAL QUESTION:
This looks kinda stupid. I'm sure im missing something that's very simple, since I was able to accomplish this before. Anyways, I want to echo some text for every item in an array. This array is derived from mySQL.
here's the code
while ($row = mysql_fetch_assoc(mysql_query("SELECT * FROM files"))) {
echo $row['name'];
}
can you post the complete code? I think you forgot the database connection.
Try this:
$result = mysql_query("SELECT * FROM files") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
var_dump($row['name']);
}
This will throw an error, I guess you made a mistake over there. Also, var_dump() your $row in the while to make 100% sure you have "a" value.
Also, are you sure the row does exist? If don't have any records, the echo on your $row will not work sinc it does not exist.
Also, set error reporting to E_ALL like so.
error_reporting(E_ALL);
Also, since you are running your query inside the while() loop, it will continue to run forever. So first run the query, and put it in a variable, and then loop through the results. (see my piece of code above)
You can execute query individual instead of while loop because if your query return more than 1 rows it will goes under the loop. show your loop print only first data of result and your loop is infinite.
From your question it seems so simple, try this way it's working.
$sql="SELECT name From files";
$names = $db->query($sql);
while($name1 = $db->fetchByAssoc($names))
{
echo $name1['name'];
}

How to get "field names" using PHP ADOdb?

I'm using PHP ADOdb and I can get the result set:
$result = &$db->Execute($query);
How do I get the field names from that one row and loop through it?
(I'm using access database if that matters.)
It will depend on your fetch mode - if you setFetchMode to ADODB_FETCH_NUM (probably the default) each row contains a flat array of columns. If you setFetchMode to ADODB_FETCH_ASSOC you get an associative array where you can access each value by a key. The following is taken from ADODB documentation - http://phplens.com/lens/adodb/docs-adodb.htm#ex1
$db->SetFetchMode(ADODB_FETCH_NUM);
$rs1 = $db->Execute('select * from table');
$db->SetFetchMode(ADODB_FETCH_ASSOC);
$rs2 = $db->Execute('select * from table');
print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1')
print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')
To loop through a set of results:
$result = &$db->Execute($query);
foreach ($result as $row) {
print_r($row);
}
Small improvement to the solution posted by #thetaiko.
If you are ONLY needing the field names, append LIMIT 1 to the end of your select statement (as shown below). This will tell the server to send you a single row with column names, rather than sending you the entire table.
SELECT * FROM table LIMIT 1;
I'm working with a table that contains 9.1M records, so this minor change speeds up the query significantly!
This is a function I use to return a field array - I've stripped out some extra stuff that, for example, allows it to work with other DBs than MySQL.
function getFieldNames($strTable, $cn) {
$aRet = array();
# Get Field Names:
$lngCountFields = 0;
$strSQL = "SELECT * FROM $strTable LIMIT 1;";
$rs = $cn->Execute($strSQL)
or die("Error in query: \n$strSQL\n" . $cn->ErrorMsg());
if (!$rs->EOF) {
for ($i = 0; $i < $rs->FieldCount(); $i++) {
$fld = $rs->FetchField($i);
$aRet[$lngCountFields] = $fld->name;
$lngCountFields++;
}
}
$rs->Close();
$rs = null;
return $aRet;
}
Edit: just to point out that, as I say, I've stripped out some extra stuff, and the EOF check is therefore no longer necessary in the above, reduced version.
I initally tried to use MetaColumnNames, but it gave differing results in VisualPHPUnit and actual site, while running from the same server, so eventually
I ended up doing something like this:
$sql = "select column_name, column_key, column_default, data_type, table_name, table_schema from information_schema.columns";
$sql .= ' where table_name="'.$table.'" and table_schema="'.$database_name.'"';
$result = $conn->Execute($sql);
while($row = $result->fetchRow()) {
$out[] = strToUpper($row['column_name']);
}
I think it should work with mysql, mssql and postgres.
The benefit of doing it like this, is that you can get the column names, even if a query from a table returns an empty set.
If you need the Coloumn names even for empty tables or for joins about multiple tables use this:
$db->Execute("SELECT .......");
// FieldTypesArray - Reads ColoumnInfo from Result, even for Joins
$colInfo = $res->FieldTypesArray();
$colNames = array();
foreach($colInfo as $info) $colNames[] = $info->name;
The OP is asking for a list of fieldnames that would result of executing an sql statement stored in $query.
Using $result->fetchRow(), even with fetch mode set to associative, will return nothing if no records match the criteria set by $query. The $result->fields array would also be empty and would give no information for getting the fieldnames list.
Actually, we don't know what's inside the $query statement. Besides, setting limit to 1 may not compatible with all database drivers supported by PHP ADOdb.
Answer by Radon8472 is the right one, but the correct code could be:
$result = $db->Execute($query);
// FieldTypesArray - an array of ADOFieldObject Objects
// read from $result, even for empty sets or when
// using * as field list.
$colInfo = [];
if (is_subclass_of($result, 'ADORecordSet')){
foreach ($result->FieldTypesArray() as $info) {
$colInfo[] = $info->name;
}
}
I have the habit of checking the class name of $result, for as PHP ADOdb will return false if execution fails.

Categories