I have this function:
function findAllmessageSender(){
$all_from = mysql_query("SELECT DISTINCT `from_id` FROM chat");
$names = array();
while ($row = mysql_fetch_array($all_from)) {
$names[] = $row[0];
}
return($names);
}
that returns all the ID of my users in a private messaging system. Then I want to get the all the messages where the user_id is equal to the user logged in and from_id is equal to all from_id I got from the previous function:
function fetchAllMessages($user_id){
$from_id = array();
$from_id = findAllmessageSender();
$data = '\'' . implode('\', \'', $from_id) . '\'';
//if I echo out $ data I get these numbers '113', '141', '109', '111' and that's what I want
$q=array();
$q = mysql_query("SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id` IN($data)") or die(mysql_error());
$try = mysql_fetch_assoc($q);
print_r($try);
}
print_r return only 1 result:
Array (
[id] => 3505
[from_id] => 111
[to_id] => 109
[message] => how are you?
[sent] => 1343109753
[recd] => 1
[system_message] => no
)
But there should be 4 messages.
You have to call mysql_fetch_assoc() for each row that is returned. If you just call mysql_fetch_assoc() once then its only going to return the first row.
Try something like this:
$result = mysql_query("SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id` IN($data)") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
'mysql_fetch_assoc' returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
You need to iterate array like:
while ($row = mysql_fetch_assoc($q)) {
echo $row["message"];
}
Related
Hi guys i would like to ask help on my problem..
I have 4 variables made from my query:
$sql1 = mysql_num_rows(mysql_query("SELECT * FROM tbl_reservation WHERE YEAR(date_added) = YEAR(NOW()) AND order_action = 'Online Transaction' "));
$sql2 = mysql_num_rows(mysql_query("SELECT * FROM tbl_reservation WHERE YEAR(date_added) = YEAR(NOW()) AND order_action = 'Walkin Transaction' "));
$sql3 = mysql_num_rows(mysql_query("SELECT * FROM tbl_reservation WHERE YEAR(date_added) = YEAR(NOW())-1 AND order_action = 'Online Transaction' "));
$sql4 = mysql_num_rows(mysql_query("SELECT * FROM tbl_reservation WHERE YEAR(date_added) = YEAR(NOW())-1 AND order_action = 'Walkin Transaction' "));
I would like to put them in an array..to be exactly on my expectations.
Here is my sample code:
$stack = array($sql1, $sql2);
array_push($stack, $sql3, $sql4);
$query = print_r($stack);
$result = $query;
print json_encode($result);
It display like this on my browser:
Array ( [0] => 0 [1] => 8 [2] => 0 [3] => 1 ) true
But i want to display it like this:
[{"0","1"},
{"2","3"}]
I am planning to make a line graph on this.. I have a Chart.min.js and jquery.min.js
If any way.. The whole point.. i want to make a line graph that would compare my data from current year to last year.
Help me pls. :(
Give a try
<?php
$a = array(0,8,0,1) ;
echo "<pre>";print_r(json_encode(array_chunk($a, 2)));
?>
with that. You can get this result
[[0,8],[0,1]]
Btw, Why you need to do that with your array ? .
Edited
After i check your question again, So you want get the order
<?php
$stack = array(0,8,0,1) ;
$array2= array();
foreach ($stack as $key => $val) {
$array2[] = $key;
}
echo "<pre>";print_r(json_encode(array_chunk($array2, 2)));
?>
my database table is named order. it has a row like order. I store values like this 1,2,3,4,5. Now i would like to add to array and from it out info..
I tried to do that but it is not working...
here is my code:
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
if want check print_r($array) Output
Array ( [0] => 1,23,4,5 )
this one is not working.. i think its supposed to be like this: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
FASTEST APPROACH
You need to use explode() function. Here is an example of it :
<?php
$array = array('0' =>'1,2,3,4,5');
$array = explode(',', $array[0]);
var_dump($array);
?>
Here is your updated code, to get array in that format.
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
$array = explode(',', $array[0]);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
Note this is solution which you are looking for. But it isn't recommended due to reason told to you as comment.
PROPER WAY TO HANDLE THIS
You should ideally normalize your Database so this kind of problem don't come even in future to you.
Here is a proposed table structure change, which you can consider, depending on your need & time.
Remove order column from your table. Add a new table named order_suborders as follows:
| COLUMN | TYPE |
|:-----------|------------:|
|parent_order| int |
| order_id | int |
You can change name of columns and table according to your wish.
Move old data accordingly.
Use query SELECT order_suborders.order_id FROM order, order_suborders WHERE order.id = ".$_GET['id']." AND order.id = order_suborders.parent_order
you can use explod to split with ","
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
//$array = array($sql_order);
$array=explod(",",$sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
The code I have is the following
$sql = <<<SQL
SELECT p . * , s . *
FROM am_user p
INNER JOIN am_user_status s
USING ( user_id )
WHERE product_id =4
AND partner_logo = '1'
ORDER BY RAND( )
LIMIT 6
SQL;
$array = Array();
while ($row = mysql_fetch_array($result)) {
$array[] = $result;
}
echo $array;
However I am getting an error, I am just trying to get the results into an array. Does anyone know how I can achieve this?
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /var/sites/c/xxxxxxx/public_html/index.php on line 26
Thanks!
$sql = mysql_query("
SELECT p . * , s . *
FROM am_user p
INNER JOIN am_user_status s
USING ( user_id )
WHERE product_id =4
AND partner_logo = '1'
ORDER BY RAND( )
LIMIT 6";
$array = Array();
while ($row = mysql_fetch_array( $sql )) {
$array[] = $row;
}
echo "<pre>";
print_r( $array );
You have the sql statement, byt forgot to send it to mysql.
...
$result = mysql_query($SQL); // you forgot this
$array = Array();
while ($row = mysql_fetch_array($result)) {
$array[] = $result;
}
var_dump($array) ; // not echo $array
I want to retrieve the data from db using PHP
$device_owner_resultset=mysqli_query($con, "SELECT * FROM `device_owner_details` WHERE `deviceId` =$device_details_data_id");
$device_owner_resultset_data = mysqli_fetch_array($device_owner_resultset);
$owner_deviceid = $device_owner_resultset_data['deviceId'];
$owner_name = $device_owner_resultset_data['name'];
$name_fetch_rows = mysqli_fetch_row($device_owner_resultset);
$device_realtime_resultset=mysqli_query($con, "SELECT * FROM `device_realtime_stats` WHERE `deviceId` = $owner_deviceid LIMIT $start_from , $limit");
$rows_fetch = mysqli_fetch_row($device_realtime_resultset);
if(($total_pages<=$page) &&( $total_pages>0))
{
$device_details=array('devices'=> array());
for($i=1;$i<=20;$i++)
{
$details =array('name' => $name_fetch_rows[$i]-> name, 'latitude' => $rows_fetch[$i] -> currentLatitude, 'longitude' => $rows_fetch[$i] -> currentLongitude);
array_push($device_details['devices'],$details);
}
$response = json_encode($device_details);
echo $response;
}
Here i have an parse error, what is the mistake from my coding , i think error is in mysqli_fetch_rows and its calling array
You are not using mysqli_fetch_row($result) correctly. The function mysqli_fetch_row($result) does not return all the row data. It returns an array of a single row as an enumerated array. Try this code using this code instead:
// Now only selects name column and added LIMIT 1 to MySQL query for efficiency
$device_owner_resultset = mysqli_query($con, "SELECT name FROM `device_owner_details` WHERE `deviceId` = $device_details_data_id LIMIT 1");
// Now using mysqli_fetch_assoc($result)
// instead of mysqli_fetch_array($result) for clarity
$device_owner_resultset_data = mysqli_fetch_assoc($device_owner_resultset);
// Got rid of $owner_deviceid because it should be the same as $device_details_data_id
$owner_name = $device_owner_resultset_data['name'];
// Got rid of $name_fetch_rows because it is redundant with $device_owner_resultset_data
// Query now specifies which columns it selects for clarity and efficiency
$device_realtime_resultset = mysqli_query($con, "SELECT currentLatitude, currentLongitude FROM `device_realtime_stats` WHERE `deviceId` = $device_details_data_id LIMIT $start_from, $limit");
if ($total_pages <= $page && $total_pages > 0) {
$device_details=array('devices'=> array());
// This loops through all the rows from the query
while ($row = mysqli_fetch_assoc($device_realtime_resultset)) {
// $row is an associative array where the column name is
// mapped to the column value.
// The owner name should remain the same because there is
// only one owner.
$details = array('name' => $owner_name,
'latitude' => $row["currentLatitude"],
'longitude' => $row["currentLongitude"]
);
array_push($device_details['devices'], $details);
}
$response = json_encode($device_details);
echo $response;
}
If the columns of the device_realtime_stats table are not named currentLatitude and currentLongitude make sure they are renamed.
$mysql_all_resultset = mysqli_query($con, " SELECT dot.name, drs.currentLatitude, drs.currentLongitude FROM device_details dt, device_owner_details dot, device_realtime_stats drs WHERE dt.vendorId=$vendor_id AND dot.deviceId=dt.id AND drs.deviceId= dot.deviceId LIMIT $start_from, $limit ");
if(($total_pages<=$page) &&( $total_pages>0))
{
$device_details=array('devices'=> array());
while ($rows_fetch = mysqli_fetch_assoc($mysql_all_resultset))
{
$details =array('name' => $rows_fetch['name'], 'latitude' => $rows_fetch['currentLatitude'], 'longitude' => $rows_fetch['currentLongitude']);
array_push($device_details['devices'],$details);
}
$response = json_encode($device_details);
echo $response;
}
I have this code
if(!isset($_GET['album_id'])) { die("Album Not Found!"); } else { $album_id = mysql_real_escape_string($_GET['album_id']); }
$sql = "SELECT * FROM `audio_albums` WHERE `album_id` = ".$album_id."";
$qry = mysql_query($sql);
$num = mysql_num_rows($qry);
if($num == 1) {
// Fetch Array
$arr = mysql_fetch_array($qry);
// Assign Values
$album_name = $arr['album_name'];
$album_name_seo = $arr['album_name_seo'];
$album_id = $arr['album_id'];
// Fetch Songs
$sql2 = "SELECT audio_id,album_id,title FROM `audios` WHERE `album_id` = ".$album_id." AND `public_private` = 'public' AND `approved` = 'yes' LIMIT 0, 30 ";
$qry2 = mysql_query($sql2);
$arr2 = mysql_fetch_array($qry2);
print_r($arr2);
} else {
echo "Album Not Found!";
}
and when i execute the code, it results in this
Array
(
[0] => qCpPdBZIpkXfVIg4iUle.mp3
[audio_id] => qCpPdBZIpkXfVIg4iUle.mp3
[1] => 1
[album_id] => 1
[2] => Ambitionz Az a Ridah
[title] => Ambitionz Az a Ridah
)
Actually it fetches data of only one row but there are several rows in result. Whats wrong in the code? why isn't it working?
Well, mysql_fetch_array fetches one row. You just need to do a loop to fetch all of them, as the manual shows: http://php.net/mysql_fetch_array
while ($arr2 = mysql_fetch_array($qry2)) {
print_r($arr2);
}
You really should learn some SQL ( yes , actually learn it ), and stop using the horribly outdated mysql_* functions.
$stmt = $dbh->prepare('
SELECT
audios.audio_id AS audio_id
audio_albums.album_id AS album_id
audios.title AS title
audio_albums.album_name AS album
audio_albums.album_name_seo AS seo_album
FROM audios
LEFT JOIN audio_albums USING (album_id)
WHERE
audio_albums.album_id = :id
audios.public_private = "public" AND
audios.approved = "yes"
LIMIT 0, 30
');
$stmt->bindParam( ':id', $_GET['album_id'], PDO::PARAM_INT );
if ( $stmt->execute() )
{
var_dump( $stmt->fetchAll(PDO::FETCH_ASSOC) );
}else{
echo 'empty .. try another';
}