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'];
}
Related
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'];
I´m trying to select all the rows from db but it´s not returning me all the rows. What am I doing wrong below?
$conn=mysql_connect('localhost:3307', 'root', 'usbw');
mysql_select_db('android',$conn);
mysql_set_charset('utf8',$conn);
$response=array();
$result=mysql_query("select * from news");
if(mysql_num_rows($result)>0){
while($row=mysql_fetch_array($result)){
$temp=array();
$temp["ID"]=$row["ID"];
$temp["TitrNews"]=$row["TitrNews"];
$temp["MiniMatnNews"]=$row["MiniMatnNews"];
$temp["MatnNews"]=$row["MatnNews"];
$temp["TArikh"]=$row["TArikh"];
}
$response["news"]=array();
array_push($response["news"],$temp);
$response["t"]=1;
echo json_encode($response);
}
else {
$response["t"]=0;
$response["massage"]="peyda nashod";
echo json_encode($response);
}
Is there something wrong with this code? My output only displays the last row of my database
{"news":[{"ID":"7","TitrNews":"hi","MiniMatnNews":"hello","MatnNews":":D","TArikh":"1395-09-08"}],"t":1}
You must declare
$response["news"]=array();
outside (i.e. just before) of the while loop. In fact, you may also don't declare it, as $response = array(); is enough to set our variable (and even dispensable ?).
Now, just before adding our $temp result, we reset the result container,so you only were seeing the last result !
AND :
array_push($response["news"],$temp);
must be in the wile loop, as we want to add each individual row to the final array.
Here is the way i would have choose :
$conn=mysql_connect('localhost:3307', 'root', 'usbw');
mysql_select_db('android',$conn);
mysql_set_charset('utf8',$conn);
$response=array();
$result=mysql_query("select * from news");
if(mysql_num_rows($result)>0){
while($row=mysql_fetch_array($result)){
$temp=array();
$temp["ID"]=$row["ID"];
$temp["TitrNews"]=$row["TitrNews"];
$temp["MiniMatnNews"]=$row["MiniMatnNews"];
$temp["MatnNews"]=$row["MatnNews"];
$temp["TArikh"]=$row["TArikh"];
// add a new element to the response["temp"] array, containing our result
$response["news"][]=$temp;
}
$response["t"]=1;
echo json_encode($response);
}
else {
$response["t"]=0;
$response["massage"]="peyda nashod";
echo json_encode($response);
}
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();
}
Please see the below code.
I am trying to retrieve the most recent two "element_value"s from my database table and then put them into a different table, with one column each. I can do this part with a mysql insert statement if I can get them into variables within the PHP, at the moment I have them being echoed out to the screen instead.
Does anyone know please how I can get them into two separate variables instead?
Thanks!
//Connect to database
$con=mysqli_connect("localhost","user","pass","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL database: " . mysqli_connect_error();
}
//Query the database
$result = mysqli_query($con, 'SELECT element_value FROM wp_formmaker_submits ORDER BY id DESC LIMIT 2;');
//Process the results
if (mysqli_num_rows($result) > 0) {
while ( $dataValue = mysqli_fetch_row($result))
echo "<p>".$dataValue[0]."</p>";
}
Change :
while ($dataValue = mysqli_fetch_row($result))
echo "<p>".$dataValue[0]."</p>";
To this :
$values = null;
while ($dataValue = mysqli_fetch_assoc($result))
{
$values[] = $dataValue['element_value'];
}
print_r($values);
This will store your values in an array, I've added print_r at the end just so you can see the resulting data structure.
If you want to display them in an array again, you can do this :
foreach ($values as $value)
{
echo "<p>".$value."</p>";
}
I've changed your fetch_row method for fetch_assoc, an explanation can be found here : https://stackoverflow.com/a/9540590/2483649
Ok i got a problem now i want to display a data from the database and display it through a function now how do i do that??
like i have fetched a row from the database and its name is $row_field['data']; and it is correct now i have assigned a variable to it like this $data = $row_field['data']; now if i call it in a function it shows undefined variable even after i assigned it global in the function like this
function fun(){
global $data;
echo $data;
}
but if i assign it a value like 1 or 2 or anything it gets displayed without any error why is that so??
If it displays if you assign it a value like 1 or 2 while still in the global scope, then I can only assume that your database did not return the result you thought it did. Does the database value display if you echo it out outside of the function?
Global is evil. I dont know what you are trying to do, but why dont you just do the query in the function itself?
If you have a column named data and your php call was something like
$result = mysql_query("SELECT data FROM mytable");
while ($row_field = mysql_fetch_assoc($result, MYSQL_NUM)) {
...
}
Then you could replace ... with print $row_field['data'].
Else please provide a snippet of your code where you query the db and retrieve the result.
When learning php try to start with simple things. For example in order to get some data from a database follow the examples from php website.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
If all this goes well go a little further change a little the while loop.
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$myArray[] = $row;
}
mysql_free_result($result);
// now you can start playing with your data
echo $myArray[0];
Small steps...