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

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

Related

update data multiple codeigniter

hello i have data array
function help_upd2($id)
{
$sql = $this->db->query("SELECT * FROM outbound WHERE id_outbound_voice='$id' ")->result();
$data = array();
foreach ($sql as $value) {
$data[] = $value->qty_outbound;
}
echo "<pre>", print_r($data);
// $a = $data * 100000;
// $this->db->query("UPDATE outbound SET total = '$a' WHERE id_outbound_voice = '$id'");
}
$data output ->
Array
(
[0] => 5 // * 100000
[1] => 1 // * 100000
[2] => 1 // * 100000
)
here I want to update the output value * 100000
When you are fetching from db it pulls them as string so you need to cast int on them to make math operations. Do this in the loop $data[] = (int) $value->qty_outbound * 100000;

I want to put a while loop into an array

I have a multidimensional array where under "images" I want to loop 4 rows from my database. It means I am trying to put a loop into an array. Help me.
$sql_album = "SELECT * FROM albums";
$res_album = mysql_query($sql_album) or die(mysql_error());
$albums = array();
while ($row_album = mysql_fetch_assoc($res_album)) {
$albums[$row_album['title']] = array(
"description" => $row_album['description'],
"date" => $row_album['date'],
"images" => array(
//i want to insert a loop here shown down
)
);
}
This is the loop i want to insert where i wrote the comment in the upper script:
$sql_thumb = "SELECT * FROM photos WHERE album_id = '".$row_album['id']."' LIMIT 0, 4";
$res_thumb = mysql_query($sql_thumb) or die(mysql_error());
while ($row_thumb = mysql_fetch_assoc($res_thumb)) {
echo $row_thumb['thumb_url'];
}
Start here...
include('../path/to/mysqli/connection/statements');
$query = "
SELECT a.id
, a.title
, a.description
, a.date
, p.thumb_url
FROM albums a
LEFT
JOIN photos p
ON p.album_id = a.id
ORDER
BY a.id;
";
$result = mysqli_fetch_assoc($db,$query);
Sadly PHP does not allow this kind of usage. You could however do something like this
$sql_album = "SELECT * FROM albums";
$res_album = mysql_query($sql_album) or die(mysql_error());
$albums = array();
while ($row_album = mysql_fetch_assoc($res_album)) {
$albums[$row_album['title']] = array(
"description" => $row_album['description'],
"date" => $row_album['date'],
"images" => array()
);
$sql_thumb = "SELECT * FROM photos WHERE album_id = '".$row_album['id']."' LIMIT 0, 4";
$res_thumb = mysql_query($sql_thumb) or die(mysql_error());
while ($row_thumb = mysql_fetch_assoc($res_thumb)) {
$albums[$row_album['title']]["images"][] = row_thumb['thumb_url'];
}
}

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

splitting an array with single key and string value into an array with multiple keys and values

I have a table which stores the courses registered by students during a semester and session. I populated it with course-codes for a particular student. Here is the function that fetches the course-code below:
function get_course_code(){
global $connection;
$query = "SELECT DISTINCT course_code ";
$query .= "FROM tbl_registered_courses_400 ";
$query .= "WHERE matric_no = '03/55ec101' LIMIT 10";
$course_code_set = mysql_query($query, $connection);
confirm_query($course_code_set);
return $course_code_set;
}
When I called the function in my main page. It returned the following result
$courseCode = get_course_code();
$courseFilter = '';
while ($courseList = mysql_fetch_array($courseCode)){
$courseList['course_code'];
$courseFilter .= "\""."{$courseList['course_code']}"."\",";
$courseFilter;
}
$course = array($courseFilter);
print_r($course);
Array ( [0] => "PHY 432","CSC 491","CHM 401","CHM 402","MAT 451","MAT 452","CSC 423","BLY 401", )
I want to split the $course array into an array that will have the values of the string in the above to read
array(
[0] => PHY 432
[1] => CSC 491
[2] => CHM 401
[3] => CHM 402
.
.
.
e.t.c
)
The string data in the $course array is from the course_code column in the database.
My intention is to use the results of the new array to form a row in the database that will hold the results of each matric_no for different courses done for the semester/session. I would appreciate any help I can get to get this done.
create the array and then assign the values to that array.
$courseCode = get_course_code();
$course = array();
while ($courseList = mysql_fetch_array($courseCode)){
$course[] = $courseList['course_code'];
}
print_r($course);

mysql statement not working

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

Categories