Store Column Values in Array - php

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;
}

Related

implode output does not gives proper output

This shows all the elements from an array in a string but without a separator. I used ',' as a separator in this code. And it does not work. How can i separate them with separator.
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Database Connection failed.".mysql_error());
}
$db = mysql_select_db("test1",$con);
if(!$db)
{
die("Database selection failed.".mysql_error());
}
$query = "select * from menu limit 10";
$result = mysql_query($query,$con);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
//$menu_name = $row['m_name'];
//$menu_image = $row['m_image'];
$menu_name = array($row['m_name']);
$menu_image = array($row['m_image']);
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
}
if(!$result)
{
echo mysql_error;
}
?>
you are storing array into variable . so if you will use imploade on an variable it will not show the result so best way is to store your result into an array and then use implode .
Don't use depricated mysql_* function use mysqli_* or pdo
instead
$menu_image=array(); // start array to store
$menu_name=array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name']; // store menu name
$menu_image[] = $row['m_image']; // store menu image
}
echo implode(',',$menu_name); // finaly use implode
You can try this:
$menu_name[];
$menu_image[];
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$menu_name[] = $row['m_name']; // I change your $menu_name into an array so that when you fetch $row['m_name'] it returns an array
$menu_image[] = $row['m_image']; //same thing
}
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
try this in place of your while loop
$menu_name = array();
$menu_image = array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name'];
$menu_image[] = $row['m_image'];
}
echo implode(',',$menu_name);

remove last character

i noticed that there are a lot of topics like this in stackoverflow, but the ones that i read are with just 1 variable, and i have two and i'm a little confuse.
so this is my code,
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
while($row = mysql_fetch_array($query)){
echo "'".$row['provider_id']."':'".$row['company_name']."',";
}
I am using this to generate javascript code for Jeditable.
I need to take out the last comma, so I can wrap up with the rest of the code...
I like to use an array:
$query = ...;
$out = Array();
while($row = mysql_fetch_assoc($query)) {
$out[] = "'".$row['provider_id']."':'".$row['company_name']."'";
}
echo implode(",",$out);
It looks like you're trying to output some kind of JSON though, so perhaps you could use:
$query = ...;
$out = Array();
while($row = mysql_fetch_assoc($query)) {
$out[$row['provider_id']] = $row['company_name'];
}
echo json_encode($out);
So i usually just stack things like this into an array and then implode:
$parts = array();
while($row = mysql_fetch_array($query)){
$parts[] = "'".$row['provider_id']."':'".$row['company_name']."'";
}
echo implode(',', $parts);
That said it looks like youre outputting the body of a JSON string. If so you shouldnt manually build it you should use json_encode instead.
$data = array();
while($row = mysql_fetch_array($query)){
$data[$row['provider_id']] = $row['company_name'];
}
echo json_encode($data);
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
$result = "";
while($row = mysql_fetch_array($query)){
$result .= "'".$row['provider_id']."':'".$row['company_name']."',";
}
$result = rtrim($result, ',');
OR
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
$result = array;
while($row = mysql_fetch_array($query)){
$result[] = "'".$row['provider_id']."':'".$row['company_name']."',";
}
$result = implode(',' $result);
OR
get count of records (mysql_num_rows($query)) and when you hit last row just do what you want

php while loop only displays one result for a mysql query across multiple tables

I am having an issue with a while statement only returning one result. this is my first time trying to display product information from several tables and I don't know what I'm doing wrong. here is the code:
<?php
require('./includes/config.inc.php');
require(MYSQL);
$sql = sprintf("SELECT * FROM tea");
$res = mysqli_query($dbc, $sql);
if(!$res){
die('Could not complete query: '.mysqli_error($dbc));
} else {
echo 'Success!<br />';
while($row = mysqli_fetch_array($res)){
$table = $row['category'];
$inum = $row['item_number'];
echo $table.' '.$inum.'<br />';
$fetch = sprintf("SELECT sub_category, item_name, description FROM $table WHERE item_number ='$inum'");
$fetchRes = mysqli_query($dbc, $fetch);
if(!$fetchRes){
die('Could not fetch: '.mysqli_error($dbc));
} else {
while($fetchRow = mysqli_fetch_array($fetchRes)){
$subCat = $fetchRes['sub_category'];
$iNumber = $inum;
$iname = $fetchRes['item_name'];
$desc = $fetchRes['description'];
echo $id.' '.$subCat.' '.$iNumber.' '.$iname.' '.$desc.'<br />';
}
}
}
}
Inside your while loop, you should be using the $fetchRow variable as the array from which to grab columns, such as 'sub_category'.
IS
$subCat = $fetchRes['sub_category'];
$iNumber = $inum;
$iname = $fetchRes['item_name'];
$desc = $fetchRes['description'];
Needs to be: Res to Row
$subCat = $fetchRow['sub_category'];
$iNumber = $inum;
$iname = $fetchRow['item_name'];
$desc = $fetchRow['description'];

Populate array from while loop to return PHP

Hi im trying to populate an array with indexes like 'user1' and 'score1' to return to a function.
My Code: It comes up with unindentified variable errors
$query = 'select * from users order by score desc';
$result = mysql_query($query) or die (mysql_error());
$highscore = array();
$count = '0';
while($row = mysql_fetch_array($result))
{
$count++;
$highscore = array('user' . $count => $row['username'], 'score' . $count => $row['score']);
}
return $highscore;
You should use numeric values when you want to use them.. You used a string representation of zero ('0')
$count = 0;
$highscore = array();
while($row = mysql_fetch_array($result))
{
$count++;
$highscore['user' . $count] = $row['username'];
$highscore['score' . $count] = $row['score'];
}
If you wanted 'high score' you might want to use max and just return 1 row.

array_push key=>value , how can do it?

I want to push key and value in array , but I can't
$con = mysqli_connect('localhost','root','','wp') or die (mysqli_error('Error:'));
$query = mysqli_query($con,'set names utf8')or die (mysql_error());
$qy = mysqli_query($con,"SELECT ID,post_title FROM wp_posts WHERE post_type='page' AND post_status='publish'")or die (mysql_error());
$arr = array();
while ($row = mysqli_fetch_array($qy)){
$id = "?page_id=".$row['ID'];
$title = $row['post_title'];
$arr[] = $id . "=>" . $title;
array_push($arr, "$id" => "$title");
}
plz help me ..
thanks ^_^
Here's what I would do instead:
$arr = array();
while ($row = mysqli_fetch_assoc($qy)){
$id = $row['ID'];
$arr[$id] = $row['post_title'];
}
And then when you need to print them:
foreach ($arr as $id => $title) {
echo "?page_id={$id}'>{$title}</a>";
// or whatever, depends on how you want to print it
}
Don't store unnecessary information (ie: ?page_id=) in arrays.
Do you want to do $arr[$id] = $title? Or do you want this:
if (!isSet($arr[$id])) {
$arr[$id] = array();
}
$arr[$id][] = $title;
The former will make it so that $arr contains $id=>$title. The latter will make it so that $arr contains $id=>array($title1,$title2,$title3) etc if there are multiples.

Categories