error printing array when looping over it - php

Sorry for the relatively newbie question.
Ive been stuck the past hour trying to figure out why the array named $propname does not want to print when i loop over it. Here follows my code
$result = mysql_query("SELECT * FROM `player_info` WHERE `position` = 'THP'") or die(mysql_error()) ;
while($row = mysql_fetch_array($result)) //create arrays
{
$id[] = $row['player_id'];
$propName[] = $row['name'];
$propLastName[]= $row['surname'];
}//end while
//create variables for looping
$x = sizeof($propName);
$index = 0;
while($index < $x) //print variables
{
echo $propName[$index];
$index ++;
}

Just simplify your code
$result = mysql_query("SELECT * FROM `player_info` WHERE `position` = 'THP'") or die(mysql_error()) ;
while($row = mysql_fetch_array($result)) //create arrays
{
echo $row['name'];
}

$result = mysql_query("SELECT * FROM `player_info` WHERE `position` = 'THP'") or die(mysql_error()) ;
while($row = mysql_fetch_assoc($result)) //create arrays
{
$id = $row['player_id'];
echo $propName = $row['name'];
$propLastName = $row['surname'];
}

Related

Form json using php json_encode failed

By using below code
$data = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data['title'] = $row['title'];
$data['name'] = $row['name'];
}
}
echo json_encode($data);
I got 1 result, I can get full result if I do $data[] = $row['title'], but I want to make the result like this
{'title' : ['title 1','title 2'], 'name':['John','Amy']}
You are overwriting the title in each loop iteration. You need to accumulate all the titles and then set it in your data array.
$data = array();
$sql = "SELECT title FROM mainlist";
$result = $db->query($sql);
$titles = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
}
}
$data['title'] = $titles;
echo json_encode($data);
The easiest away is probably this:
$rows = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
}
echo json_encode($rows);
you could achieve by using group_concat on each of the columns in your query. That way you do not need to loop the result again and add column etc...
$sql = "SELECT group_concat(title) as title,group_concat(name) as name FROM list";
$result = $db->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Try this:
$titles = array();
$names = array();
$sql = "SELECT title,name FROM mainlist";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
$names[] = $row['name'];
}
}
echo json_encode(array("title" => $titles, "name" => $names));
UPDATE
Updated my code to let you manage an undefined number of columns as result
$out = array();
$sql = "SELECT * FROM wp_cineteca";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$keys = array_keys($row);
for ($i = 0; $i < count($row); $i++) {
$out[$keys[$i]][] = $row[$i];
}
}
}
echo json_encode($out);

SQL query not showing more than 1 row

This is the entire code the error must be in query 3 or 4. As you can see query 3 just gets info to build query 4 which should return the results.
I've got query 1 & 2 working ok which have the correct data showing.
<?php
session_start();
//printf('<pre>%s</pre>', print_r($_SESSION, true));
require('includes/config.inc.php');
require('includes/session.php');
//WORKING
DB_Connect();
$query = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'product' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result = mysql_query( $query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$hash = $row['hash'];
$foreignid = $row['foreign_id'];
$qty = $row['cnt'];
}
$query2 = "SELECT * FROM food_delivery_products WHERE food_delivery_products.id = ".$foreignid."";
$result2 = mysql_query( $query2) or die(mysql_error());
while($row = mysql_fetch_array($result2))
{
$name = $row['name'];
$description = $row['description'];
}
//---------------------------------------------------------------------------------------------------------------
$query3 = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'extra' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result3 = mysql_query( $query3)or die(mysql_error()) ;
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
}
$query4 = "SELECT * FROM food_delivery_extras WHERE food_delivery_extras.id = ".$foreignidextra."";
$result4 = mysql_query( $query4) or die(mysql_error());
while($row = mysql_fetch_array($result4))
{
$nameextra = $row['name'];
}
echo $nameextra;
echo $qtyextra;
DB_Disconnect();
//$products = implode(", ",$_SESSION['pdf_quote']['product_arr']);;
//print $products
?>
print $row; is only valid inside the loop if you want to print all of them. Otherwise it will print only the last $row. Make it
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
print $row;
}
its because you are printing the $row after the while loop gets executed
So it only prints the final result set
Use something like this instead:
$query3 = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'extra' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result3 = mysql_query( $query3) ;
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
print_r($row);
}
you can also use the var_dump($row); instead of print_r($row);
this will output all the values stored in the $row array each time the loop iterates

Why does this query show only one result?

The query I have below will only show me one result even if there are multiple matching entries (completely or partially matching). How do I fix it so it will return all matching entries:
//$allowed is a variable from database.
$sql = "SELECT `users`.`full_name`, `taglines`.`name`, `users`.`user_id` FROM
`users` LEFT JOIN `taglines` ON `users`.`user_id` = `taglines`.`person_id`
WHERE ( `users`.`user_settings` = '$allowed' ) and ( `users`.`full_name`
LIKE '%$q%' ) LIMIT $startrow, 15";
$result = mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$num_rows1 = mysql_num_rows($result);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$person = htmlspecialchars($row['full_name']);
}
}
}
print $person;
Because your overwriting $person on each iteration.
Hold it in a $person[] array if your expecting more then one. Then loop through it with a foreach loop when you intend to output.
Not related but your also querying twice, you only need 1 $result = mysql_query($sql);
Update (Simple Outputting Example):
<?php
$person=array();
while($row = mysql_fetch_array($query)){
$person[] = array('full_name'=>$row['full_name'],
'email'=>$row['email'],
'somthing_else1'=>$row['some_other_column']);
}
//Then when you want to output:
foreach($person as $value){
echo '<p>Name:'.htmlentities($value['full_name']).'</p>';
echo '<p>Eamil:'.htmlentities($value['email']).'</p>';
echo '<p>FooBar:'.htmlentities($value['somthing_else1']).'</p>';
}
?>
Or an alternative way to is to build your output within the loop using concatenation.
<?php
$person='';
while($row = mysql_fetch_array($query)){
$person .= '<p>Name:'.$row['full_name'].'</p>';
$person .= '<p>Email:'.$row['email'].'</p>';
}
echo $person;
?>
Or just echo it.
<?php
while($row = mysql_fetch_array($query)){
echo '<p>Name:'.$row['full_name'].'</p>';
echo '<p>Email:'.$row['email'].'</p>';
}
?>

Store Column Values in Array

I'm trying to store the title(summary) and date(created) of an event in an array. But I think im missing something in my loop.
<?php
$summary = array();
$date = array();
mysql_connect('mysql.server', 'myUsername', 'myPass') or die('Could not connect: ' . mysql_error());
mysql_select_db("mxgsite") or die(mysql_error());
$query_summary = mysql_query('SELECT summary FROM event_info') or die(mysql_error());
$query_date = mysql_query('SELECT created FROM event_details') or die(mysql_error());
$row_summary = mysql_fetch_array($query_summary);
$row_date = mysql_fetch_array($query_date);
$i = 0;
while(($row1 = mysql_fetch_array($query_summary))) {
$row2 = mysql_fetch_array($query_date);
$summary[] = $row['summary'];
$date[] = $row['created'];
echo $summary[$i] . " " . $date[$i] . "<br ?>";
$i++;
}
I know i'm getting values because I can echo out 1 value, but if I want to put all the values in an array and try to echo out that array I keep getting blank values?
It seems to me like you are trying to do too many things here. Since the 2 sets of values are not being stored in a way where they are related/linked to each other, you might as well deal with them in separate while loops. Try something like this:
while ($row = mysql_fetch_array($query_summary)){
$summary[] = $row[0];
}
while ($row = mysql_fetch_array($query_date)){
$date[] = $row[0];
}
If you want to relate the tables, per the comments above, you can try something more like:
$result = mysql_query('SELECT a.eventid, a.summary, b.created
FROM event_info a
join event_details b
on a.eventid = b.eventid');
$events = array();
while ($row = mysql_fetch_array($result)){
$event = array();
foreach ($row as $key=>$value){
$event[$key]=$value;
}
$events[] = $event;
}

Set value of multidimensional array

I'm currently adding fileID to idarray[] and then do a foreach. But in addition to fileID I also need serverID and id in the array and the foreach, how do I do this? So basically I need to find out how to add 2 more values to the array and then also use those extra values in the foreach.
$result = mysql_query("SELECT * FROM redundfiles WHERE removed=1");
while($row = mysql_fetch_array($result))
{
$idarray[] = $row['fileID'];
}
foreach ($idarray as $value)
{
$result = mysql_query("SELECT * FROM redundfiles WHERE fileID=$value AND removed=0 AND serverID=$XXXserverIDhereXXX");
while($row = mysql_fetch_array($result))
{
$sql = "DELETE FROM redundfiles WHERE id='".$XXXidhereXXX."' ";
mysql_query($sql) or die(mysql_error());
}
}
Why not just store the whole row into an array?
$rowarray[] = array();
$result = mysql_query("SELECT * FROM redundfiles WHERE removed=1");
while($row = mysql_fetch_array($result))
{
$rowarray[] = $row;
}
foreach ($rowarray as $row)
{
$fileid = $row['fileID'];
$serverid = $row['serverID'];
$result = mysql_query("SELECT * FROM redundfiles WHERE fileID=$fileid AND removed=0 AND serverID=$serverid");
while($row = mysql_fetch_array($result))
{
$sql = "DELETE FROM redundfiles WHERE id='".$XXXidhereXXX."' ";
mysql_query($sql) or die(mysql_error());
}
}
But really, your whole code piece here is a mess. You can accomplish this way more efficiently using JOINs.

Categories