mysql statement not working - php

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

Related

How to retrieve result set from MySQL case query in PHP

I've been looking for an answer to this all afternoon so far and cannot come up with anything yet.
I have the following MySQL PDO query:
$q = "select recip_id,
sum(case when msg_read = '0' AND msg_deleted = '0' then 1 else 0 end) uu,
sum(case when msg_read = '0' AND msg_deleted = '1' then 1 else 0 end) ud,
sum(case when msg_read = '1' AND msg_deleted = '0' then 1 else 0 end) ru,
sum(case when msg_read = '1' AND msg_deleted = '1' then 1 else 0 end) rd,
count(*) as total
from messages where recip_id = :d GROUP BY recip_id WITH ROLLUP";`
which, when I use recip_id = 18 for an example in PHPMyAdmin gives me the following table:
I have tried several ways to fetch the resulting row in php so that I can use the values for another task, to no avail. I've tried this:
$stmt = $dbo->prepare($q);
$row = $stmt->execute(array(":id" => $id));
$total = $row['total'];
$uu = $row['uu'];
$ud = $row['ud'];
$ru = $row['ru'];
$rd = $row['rd'];
echo "Recipient id: $id, Total: $total, UU: $uu, UD: $ud, RU: $ru, RD: $rd";
And this:
$stmt = $dbo->prepare($q);
$stmt->bindParam(":id", $id);
$msgcount = array();
while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$total = $row->total;
$uu = $row->uu;
$ud = $row->ud;
$ru = $row->ru;
$rd = $row->rd;
}
echo "Recipient id: $id, Total: $total, UU: $uu, UD: $ud, RU: $ru, RD: $rd";
and this too:
$msgcount = array();
$stmt = $dbo->prepare($q);
$stmt->bindParam(":id", $id);
while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
array_push($msgcount, array($row['uu'], $row['uu'], $row['ud'], $row['ru'], $row['rd']));
}
echo $msgcount[];
I cannot retrieve the values using my PHP script from the MySQL result set. I've tried serialize() on the rows and whole result set, I've tried to use PDO::FETCH_ASSOC and also unspecified fetch() and fetchAll(). *'ve used different combos and just get an empty result set or *I can't find an answer anywhere either. Can anyone help me with this please?
In your first attempt you forget to $stmt->fetch, and in the last two you forget $stmt->execute. Try this:
$stmt = $dbo->prepare($q);
if ( ! $stmt->execute(array(":id" => $id)) ) die("error"); // returns true or false
$row = $stmt->fetch(); // add this line!
$total = $row['total'];
$uu = $row['uu'];
$ud = $row['ud'];
$ru = $row['ru'];
$rd = $row['rd'];
echo "Recipient id: $id, Total: $total, UU: $uu, UD: $ud, RU: $ru, RD: $rd";

php push the results to an array by getting from the table

I have tables like this
listing_id
1
4
345
654
listing documents
listing_id folder filename
000345 full_menu_file testfile098
000345 header_menu_file testfile067
000004 full_menu_file testfile
000001 menu_file testfile567
000004 footer_menu_file testfile76
000004 test_menu_file testfile65
000345 footer_menu_file testfile764
000654 footer_menu_file testfile098
000654 footer_menu_file testfile078
Now I want to make an array and put those related data in that array. So the final output will be like this
array(
[1] => Array
(
[listing_id] => 1
[full_menu_file] =>
[header_menu_file] =>
[menu_file] =>
[footer_menu_file] =>
[test_menu_file] =>
)
[1] => Array
(
[listing_id] => 345
[full_menu_file] => testfile067
[header_menu_file] => testfile067
[menu_file] =>
[footer_menu_file] => testfile764
[test_menu_file] =>
)
[2] => Array
(
[listing_id] => 4
[full_menu_file] => testfile
[header_menu_file] =>
[menu_file] =>
[footer_menu_file] => testfile76
[test_menu_file] => testfile65
)
)
So I made my php code like this
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "listings";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$listing_query = "SELECT * FROM `listings` ORDER BY `listing_id` ASC ";
$cat_array = array();
if( $result = $mysqli->query($listing_query) ) {
while( $obj = $result->fetch_object() ) {
$listing_id = $obj->listing_id;
//Get all the file names
$get_images_name = "SELECT * FROM `listing_documents` WHERE `listing_id` = ".str_pad($listing_id, 6, '0', STR_PAD_LEFT)." ";
if( $img_query = $mysqli->query($get_images_name) ) {
while( $object = $img_query->fetch_object() ) {
if( $object->folder == 'full_menu_file' ) {
$full_menu_file_name = $object->filename;
}
if( $object->folder == 'header_menu_file' ) {
$header_menu_file_name = $object->filename;
}
if( $object->folder == 'menu_file' ) {
$menu_file_name = $object->filename;
}
if( $object->folder == 'footer_menu_file' ) {
$footer_menu_file_name = $object->filename;
}
}
$listing_array['listing_id'] = $listing_id;
$listing_array['full_menu_file_name'] = $object->full_menu_file_name;
$listing_array['header_menu_file'] = $object->header_menu_file;
$listing_array['menu_file'] = $object->menu_file;
$listing_array['footer_menu_file'] = $object->footer_menu_file;
array_push($cat_array, $listing_array);
}
}
print_r($cat_array);
But it is not showing the result as I need. So can someone tell me how to do this? Any suggestions will be really appreciable. Thanks
You need to put quotes around the result of str_pad so it will be treated as a string, not a number with leading zeroes.
$get_images_name = "SELECT * FROM `listing_documents` WHERE `listing_id` = '".str_pad($listing_id, 6, '0', STR_PAD_LEFT)."' ";
You could also combine both queries into a single JOIN:
SELECT l.listing_id as l_listing_id, ld.*
FROM listings as l
JOIN listing_documents AS ld ON ld.listing_id = LPAD(l.listing_id, 6, '0')
ORDER BY l_listing_id
The equivalent query without a join is:
SELECT *
FROM listing_documents
WHERE listing_id IN (SELECT LPAD(listing_id, 6, 0) FROM listings)
ORDER BY listing_id
I think your problem is the str_pad. You could use CONVERT or CAST instead:
SELECT * FROM `listing_documents` WHERE CAST(listing_id AS INT) = $listing_id
SELECT * FROM `listing_documents` WHERE CONVERT(INT, listing_id) = $listing_id
Your schema doesn't make sense to me. I don't know why you would use the padded string instead of an integer in your listing_documents table. But, using your current schema you could do:
$result = $mysqli->query(
<<<'QS'
SELECT listings.listing_id, listing_documents.folder, listing_documents.filename
FROM listings
JOIN listing_documents
ON listing_documents.listing_id LIKE LPAD(CONVERT(listings.listing_id,char),6,'0')
ORDER BY listings.listing_id ASC
QS;
I'm not actually sure if you need to convert the listing_id for lpad. And It probably is more performant to convert listing_documents.listing_id to an INT like ON CONVERT(listing_documents.listing_id,UNSIGNED INTEGER) = listings.listing_id
Then to add your results to an array:
$outputData = array();
while ($object=$result->fetch_object()){
if (!isset($outputData[$object->listing_id]))
$outputData[$object->listing_id] = array();
$outputData[$object->listing_id][$object->folder] = $object->filename;
}
With this approach, if a particular listing_id in listing_documents does not have all the different folders, then the key would be skipped.
Now, $outputData will have the data with array keys being the listing IDs.
To reset the array keys, you could do:
$outputData = array_values($outputData);

SyntaxError {stack: (...), message: "Unexpected token <"} tracker.js:41 parsererror

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

How to get multiple results from SQL query

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

php mysql query statement

I'm having a problem running a sql query using php.
$sql = "SELECT * FROM ".self::$table_name;
$result = mysql_query( $sql );
$r = mysql_fetch_array( $result );
print_r( $r );
die( '<br>'.$sql );
I have around 70 records in table but i'm only getting the first record.
see example.
Array ( [0] => site_url [setting_name] => site_url [1] => http://domain.com [value] => http://domain.com )
SELECT * FROM siteconfig
When I run the query in phpmyadmin. it works fine.
You have to make a loop to grab all the results:
$r = array();
while($junk = mysql_fetch_array($result)) $r[] = $junk;
print_r($r);
Do it like below:
$sql = "SELECT * FROM ".self::$table_name;
$result = mysql_query( $sql );
while($r = mysql_fetch_array($result)){
echo $r['col1']. " - ". $r['col2'];
// your stuff
}

Categories