echo selected SQL row data using PHP - php

If I collect multiple row data from SQL, I will have to use foreach loop or something else to display that data properly.
How to use these PHP strings without using foreach loop ?
Following is my SQL query
$results = $mysqli->query('SELECT * FROM specs where id in ('.$id1.','.$id2.','.$id3.','.$id4.') ');
It will result data from 4 different rows.
The above code is just an example, below is the exact code I am using in my page.
try{
$pdo = new PDO("mysql:host=localhost;dbname=databse", "user", "password");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
// Attempt select query execution
try{
$sql = "SELECT * FROM specs WHERE id IN($id1,$id2,$id3,$id4)";
$result = $pdo->query($sql);
$results = $result->fetchAll();
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close connection
unset($pdo);
Currently, the data is displayed using the following
<tr>
<td>Brand</td>
<?php foreach ($results as $result){ ?>
<td> <strong><?php echo $result['brand']; ?></strong> </td>
<?php } ?>
</tr>
There will be total 4 results, I wan to use that 4 results separately.
If the results are
Samsung, Sony, Apple, LG - how can I echo the "Apple" only using PHP string ?

Fetch all the rows. If you have the MySQL Native Driver:
$rows = $results->fetch_all(MYSQLI_ASSOC);
Otherwise, fetch with a loop:
while($rows[] = $results->fetch_assoc());
Then you can access them by row:
echo $rows[0]['brand']; // first row
echo $rows[1]['brand']; // second row
But that's not very useful. If you have something unique that you want to use (I use brand as an example though it's probably not), then just index on that:
$rows = array_column($results->fetch_all(MYSQLI_ASSOC), null, 'brand');
// or
while($row = $results->fetch_assoc()) { $rows[$row['brand']] = $row; }
// then
echo $rows['apple']['model'];

Related

Parsing MySQL output to JSON extracting field names

I'm getting some trouble with parsing the output of MySQL query in order to feed Highcharts. The biggest problem is that I would hawe 100+ data series, and I would like to don't refer to each column name in the parsing process, now the desired output would be something like that:
[
{'name':'TS','data':[4349,4375]}
{'name':'time1','data':[503,573]}
{'name':'time2','data':[500,506]}
{'name':'time3','data':[508,649]}
]
But I'm stuck with this output, where all the data are printed in the only first array:
[
{'name':'TS','data':[4349,503,573,500,4375,506,508,649,]}
{'name':'time1','data':[]}
{'name':'time2','data':[]}
{'name':'time3','data':[]}
]
The PHP code that I'm using is the following:
<?php
try {
$con= new PDO('mysql:host=localhost;dbname=test', "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT TIME_TO_SEC(TS) as TS, TIME_TO_SEC(time1) as time1, TIME_TO_SEC(time2) as time2, TIME_TO_SEC(time3) as time3 FROM time ORDER BY TS";
//first pass just gets the column names
print "[";
$result = $con->query($query);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
//second query gets the data
$data = $con->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach ($row as $field => $value){
print "{'name':'$field','data':[";
foreach($data as $row){
foreach ($row as $name=>$value){
print " $value,";
}
}
print "]}";
}
print "]";
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
Any suggestion to how to solve that problem?
Looks like you're using $row multiple times causing the loops to create errors.
Rename your inner $row variable to something else, e.g. $innerData.
foreach ($row as $field => $value){
print "{'name':'$field','data':[";
foreach($data as $innerData){
foreach ($innerData as $name=>$innerValue){
print " $innerValue,";
}
}
print "]}";
}
But there seem to be more problems in your code.
You query the database with the $query, 2 times. You you would get 2 same result sets. Did you miss to insert the second query statement ?
Please include the results the queries will produce in mysql, without php. This way I can improve my answer or other may help you too.

PHP PDO error undefined index serial

I'm about to pull my hair out. I can't get the undefined index to go away. Basically where it says echo htmlspecialchars($r['serial']) I want it to list the item out of the database table.
<?php
try{
$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
$sql = "SELECT serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes FROM $sql_table ORDER BY serial";
$q = $conn->prepare($sql);
$q->setFetchMode(PDO::FETCH_OBJ);
while ($r = $q->fetch());
} catch (PDOEException $pe) {
die("Could not connect to the database" . $pe->getMessage());
}
?>
</div>
<?php
$r = $q->fetchAll();
echo htmlspecialchars($r['serial'])
?>
You are referring to the result as an associative array where you expect to have the key 'serial'. This is the behavior of PDO::FETCH_NAMED, not PDO::FETCH_OBJ. Just use the right fetch mode, and you should be fine:
$q->setFetchMode(PDO::FETCH_NAMED);
see the below code, the fetchAll will get the results in an associative array, so you can get the data like $row['serial'] and use it later.
also added the execute() on the pdo statement obj.
<?php
try{
$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
$sql = "SELECT serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes FROM $sql_table ORDER BY serial";
$q = $conn->prepare($sql);
$q->execute(); // make sure to add this
$results = $q->fetchAll();
foreach($results as $row) {
echo htmlspecialchars($row['serial']) . "<br>";
//if you want to use the serial later, just store it into an array
$serials [] = htmlspecialchars($row['serial']);
}
// while ($r = $q->fetch()); this is not needed because of the fetchAll statement above
}
catch (PDOEException $pe) {
die("Could not connect to the database" . $pe->getMessage());
}
?>
</div>
<?php
//$r = $q->fetchAll(); not needed here, we did it above already
?>
<?php
//echo htmlspecialchars($r['serial']); use your array from above
print_r($serials);
?>
let me know if it helps

PHP While Foreach of MySQL key

Search far and wide and couldn't find an answer so I thought it was time to post. I currently have a table of vendors. I would like to loop through each vendor using the 'skuid' value for each as it is unique, then echo other information from that row. Here's what I have so far.
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$vendorQuery = "SELECT skuid FROM vendors";
$vendorResult = mysqli_query($mysqli, $vendorQuery);
while($row = mysqli_fetch_assoc($vendorResult)) {
foreach($row['skuid'] as $vendorid) {
echo $row['skuid'];
}
} ?>
You don't need that foreach, your outer loop is enough
while($row = mysqli_fetch_assoc($vendorResult)) {
echo $row['skuid'];
}
And a single mysql query doesn't return nested levels of data so there can't be any good use cases for a nested loop in this scenario.
When this loop runs, there is always only 1 skuid per row. There is no use for another nested loop there.
Now if you want to create an array of vendors from this query and then loop over it that's a good use case. For example
while($row = mysqli_fetch_assoc($vendorResult)) {
$skuid=$row['skuid'];
$name=$row['name'];
$vendors[$skuid]=array('name'=>$name); // and other fields
}
foreach($vendors as $vendor){
echo $vendor['name'];
}

displaying results from mysql with php foreach.... very confused

Hi I'm getting confused as to how to display results with foreach loops. It seems there are slight differences depending on the structure of the array? ie if its a simple array, associative or multi-dimensional? I have looked at other answers for this site but I am still very much confused.
i have connected to mysql db with this code
try
{
$pdo = new PDO('mysql:host=localhost;dbname=****', '*****',
'*****');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$error = 'Unable to connect to the database server.' . $e->getMessage;
echo $error;
exit();
}
//next i want to retrieve the 'id' and 'name' from a db table...
$results = $pdo->query('select id, name FROM author');
//now I want to display those results on the page... i tried a foreach loop...
foreach ($results as $result) {
echo $result;
}
//but this just displays error message...
Parse error: syntax error, unexpected '$results' (T_VARIABLE), expecting '(' in C:\xampp\htdocs\Connect\admin\authors\test.php on line 6
Please help as im very confused. I just want to know how to display results from a db query like this with a foreach, and what rules apply when displaying different kinds of results from such queries.
I think it involves writing a foreach something like this ....
foreach ($results as $result=> $item) {
echo $item;
}
but i dont undertsand this either.
Any simplified approach to this would be greatly appreciated as I have been stuck on this for some time.
Thanks Rob.
$result is an array not the string.
$stmt = $pdo->prepare("SELECT id, name FROM author");
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $result) {
echo $result['id'];
echo $result['name'];
}
or print the array like this,
foreach ($results as $result) {
print_r($result);
}
You could try it with prepared statements, I always do even if I am not injecting parameters, keeps things a bit clearer.
$stmt = $pdo->prepare('select id, name FROM author');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
You can use the statement fetch method, and with the constant PDO::FETCH_ASSOC to ensure each row is an associative array.
If you're just looking to SELECT something from a database, below is the general format of what you'll need:
try {
//First, you initialise a connection to the database (in this case I'm using *constants*).
$dbh = new PDO('mysql:host=localhost; dbname='.DB_NAME, DB_USER, DB_PASS);
//Secondly, we'll prepare our query - SELECT the id and name FROM table author
$stmt = $dbh->prepare("SELECT id, name FROM author");
// Then we must execute the query
$stmt->execute();
// After execution, we must perform some function to get the results
// This function fetches ALL the results as an array so we can loop
// through them with foreach.
// (Other methods include a while loop and "fetch()" for one row at a time)
$results = $stmt->fetchAll();
// Then we just loop through everything
foreach ($results as $row) {
echo $row['id'];
echo $row['name'];
}
} catch (PDOException $e) {
echo $e->getMessage();
}

Iterating over results of PDO query

I want to run a query using PDO, based on data in the URL paramater (yes, I know that this is prone to attacks, but its internal code for a utility).
$user = 'USER';
$pass = 'PASSWORD';
$dsn = 'mysql:dbname=PRODUCTS;host=HOST';
try {
$productDB = new PDO($dsn, $user, $pass);
$productDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
$msg = 'PDO ERROR' . $e->getFile() . ' L.' . $e->getLine() . ' : ' . $e->getMessage();
die($msg);
}
if(isset($_GET['cat']))
{
$cat = $_GET['cat'];
print "cat = $cat <br>";
$products = $productDB->prepare('SELECT * FROM products WHERE cat_id LIKE ?');
$products->execute(array($cat));
$rows = $products->rowCount();
print "$rows rows returned";
?>
<table border="1">
<tr>
<td>product_id</td>
<td>product_name</td>
</tr>
<?php
foreach ($products->fetchAll() as $row) {
$id = $row['product_id'];
$product_name = $row['product_name'];
print "<tr>";
print "<th scope=\"row\"><b>$id</b></th>";
print "<td> $product_name </td>";
print "<tr>";
}
print "</table>";
}
?>
When I run this code, it prints the correct number of rows depending on the query, but does not populate the table.
I have also tried replacing the prepare and execute lines with:
$products = $productDB->query("SELECT * FROM products WHERE cat_id LIKE $cat");
Which returns the correct row count, but doesn't otherwise help.
And finally, I've tried replacing the foreach line with something like:
$rows = $products->fetchAll();
foreach ($rows as $row) {
My attempts to do the same with a fixed query all work fine, but I am having trouble working out how to place a variable element in a query, and then iterate over the results.
You're not doing anything to store the result:
$products->execute(array($cat));
needs to go in a variable:
$result = $products->execute(array($cat));
Then, instead of calling $products->fetchAll(), use $results->fetchAll():
foreach ($result->fetchAll() as $row)
I find it easier to use a $query variable (for prepare, etc) and then get the result into something like $result or $product. Makes the code a bit easier to read.
Try this (If I understood correctly) :
$products = $productDB->prepare("SELECT * FROM products WHERE cat_id LIKE :cat");
// Now, you can either do this :
$products->bindParam('cat', '%'.$cat.'%');
$products->execute();
// or you can call execute with an associative array of your parameterized query.
$products->execute(array('cat' => '%'.$cat.'%'));
// Then, get all the results like this :
$rows = $products->fetchAll();
foreach ($rows as $row) {
// Do work here ..
}
// Or, like this :
while ($row = $products->fetch(PDO::FETCH_ASSOC)) {
// Do work here ..
}
I personaly prefer the while, because you don't fetch the whole query in one var, reducing the amount of memory needed.
I also recommend you to use the FETCH_* parameter, to get only the kind of array you want.
By the way, you need to know that rowCount should not be used to count the rows returned by a SELECT. As said by php.net :
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

Categories