MySQL can't get contents of cell - php

I just dont understand:
I want to get the name of the image from MySQL table like so:
$q = "SELECT legend FROM ps_image_lang WHERE id_image=27";
$res = mysqli_query($con, $q);
print_r($res);
But in the browser window i get such output:
mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 3 [type] => 0 )
Why do i get such output and how should i do it properly ?

You forgot to fetch your result, here you go:
$q = "SELECT legend FROM ps_image_lang WHERE id_image=27";
$res = mysqli_query($con, $q);
$row = mysqli_fetch_assoc($res);
print_r($row);

You can't just only use $res. It will return resource. You must process the resource.
$q = "SELECT legend FROM ps_image_lang WHERE id_image=27";
$res = mysqli_query($con, $q);
if(!$res){
$row=mysql_fetch_row($rest);
print_r($row);
} else
echo "No row is fetched";

Okay guys, sorry, forgot to transform it to an array. Soooooooooo the solution is:
function res_to_array($res) {
//$con = con();
$count = 0;
$res_array = array();
while($row = mysqli_fetch_assoc($res)) {
$res_array[$count] = $row;
$count++;
}
return $res_array;
}
$q = "SELECT legend FROM ps_image_lang WHERE id_image=27";
$res = mysqli_query($con, $q);
$res = res_to_array($res);
print_r($res);
And now i get the contents. Sorry again for asking reaaaly basic questions. :) Or... Like Tomasz Turkowski said: just mysqli_fetch_assoc(); Again, sorry sorry soryy.

Related

creating outer array php

UPDATE: a solution has been found stated below: however new issue poses i didnt want to keep creating question so updated this one when i use ajax to pass through to html i get the following error response.forEach is not a function
where the code is as below is this because there are now 2 arrays?
$.get('php/test.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
$(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
});
});
Im Pretty naff when it comes to this type of thing but i need to try get these 2 queries added to 1 ajax I have been told i should add both queries to an outer array but im not sure how to do this and the example i got was $array = $other_array
but im not sure how to write it any help would be greatly appreaciated
$sql = "SELECT beacon,TIME_FORMAT(TIMEDIFF(max(`time`),min(`time`)), '%i.%s')
AS `delivery_avg`
FROM `test`.`test`
where date = CURDATE()
and time > now() - INTERVAL 30 MINUTE
group by beacon ";
$result = $conn->query($sql);
$sql2 = 'SELECT
*
FROM
(SELECT
beacon,location,date,
COUNT(location) AS counter
FROM `test`.`test`
WHERE `date` = CURDATE() and `time` > NOW() - interval 40 second
GROUP BY beacon) AS SubQueryTable
ORDER BY SubQueryTable.counter DESC;';
$result = $conn->query($sql2);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$result2 = mysqli_query($conn , $sql2);
$rows2 = array();
while($r = mysqli_fetch_assoc($result2)) {
$rows2[] = $r;
}
echo json_encode($rows2);
You already got most of it right. To get the data in one go, you can combine the arrays (see the line staring with $result) and then send it JSON formatted.
$sql1 = "SELECT ...";
// Query the database
$result1 = $conn->query($sql);
// Fetch the result
$rows1 = $result1->fetch_all(MYSQLI_ASSOC);
// Same for second query
$sql2 = 'SELECT ...';
$result2 = $conn->query($sql2);
$rows2 = $result2->fetch_all(MYSQLI_ASSOC);
$result = array(
'query1' => $rows1,
'query2' => $rows2
);
header("Content-Type: application/json");
echo json_encode($result);
Some more hints:
You only need to run the query once (you have ->query() and mysqli_query() in your code).
You don't need the loop to get all result rows. The function mysqli_fetch_all() does that for you.
When you have your 2 arrays with db results, you can do something like this :
$return = array (
$result,
$result2
);
echo json_encode($return);
$sendResponse = array (
'sql1' => $sqlResult1,
'sql2' => $sqlResult2
);
echo json_encode($sendResponse);
This would be a more suitable and convenient (from JavaScript size) way
$response = [];
$response['result_first_query'] = $rows;
$response['result_second_query'] = $rows2;
echo json_encode($response);

Remove text result from SQL query in PHP

i have this code :
$result = mysqli_query($conn, "SELECT SUM(angsuran) FROM `laporan` WHERE id_mustahik=".$detail_campaigner->id_mustahik."");
$row = mysqli_fetch_assoc($result);
print_r($row);
when i run this code, the result is :
Array ( [SUM(angsuran)] => 30000 )
But i want it to display just "30000" number, without "Array ( [SUM(angsuran)] => ) ".
How can i do that ?
add alias in your query like
$result = mysqli_query($conn, "SELECT SUM(angsuran) as sumtotal FROM `laporan` WHERE id_mustahik=".$detail_campaigner->id_mustahik."");
$row = mysqli_fetch_assoc($result);
echo $row['sumtotal']; //outputs 30000
I have 2 ways
Use array php
$result = mysqli_query($conn, "SELECT SUM(angsuran) FROM `laporan` WHERE id_mustahik=".$detail_campaigner->id_mustahik."");
$row = mysqli_fetch_assoc($result);
echo $row["SUM(angsuran)"]; // out 30000
Modify sql
$result = mysqli_query($conn, "SELECT SUM(angsuran) as sum FROM `laporan` WHERE id_mustahik=".$detail_campaigner->id_mustahik."");
$row = mysqli_fetch_assoc($result);
echo $row["sum"]; // out 30000

Adding to an array from $row

How do I add each result from $row to the $valueIDArray? I then want to use the $valueIDArray to get results from a second database, how do I do that?
$sql = "SELECT * FROM venue
WHERE capacity >= 'partySize'";
//step 2 - executing the query
$result =& $db->query($sql);
if (PEAR::isError($sql)) {
die($result->getMessage());
}
while($row = $result -> fetchrow()){
$valueIDArray = $row[0];
}
You should do it this way:
$valueIDArray = array()
while($row = $result -> fetchrow()){
$valueIDArray[] = $row[0];
}
Define array before loop, and in loop simple add elements to array using [] after array name
$sql = "SELECT * FROM venue WHERE capacity >= 'partySize'";
//step 2 - executing the query
$result =& $db->query($sql);
if (PEAR::isError($sql)) {
die($result->getMessage());
}
$valueIDArray = array();
while($row = $result -> fetchrow()){
$valueIDArray[] = $row[0];
}
You have to add the [] braces. Like this, you always add another entry for the row.

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

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