Appending php array values with string doesn't give expected output - php

I have database query which returns an array of string values. I want them to be comma separated and appended to another string.
$sql1 = "select location.name as name from location,destination where destination.name='".$destination."' AND location.destination_id=destination.destination_id";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
$insert = "";
while($locations = $result1->fetch_assoc()) {
foreach ($locations as $location) {
$insert .= $location['name'] . ",";
}
}
$insert = rtrim($insert, ",");
}
$sql2 = "select destination.destination_description as description from destination where destination.name='".$destination."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$response->speech = $destination." is the ".$row["description"].". ".$insert . "are some of the places you can try.";
echo json_encode($response);
}
}
This $insert array doesn't give the expected result. It gives just "N".

You can remove the line foreach ($locations as $location)
Your while already fetch all rows to locations so you just need to append your locations[‘name’]. Your foreach has retrieved each character in the string $locations

I think you should look at explode function that might help you Explode function in php

If i understand your problem. You need to use implode() function of php.Try this:-
if ($result1->num_rows > 0) {
$ImplodeArray =array();
while($locations = $result1->fetch_assoc()) {
foreach ($locations as $location) {
$ImplodeArray[] = $location['name'];
}
}
$insert = implode(',',$ImplodeArray);
echo $insert;
}
Hope it helps!

Related

PHP: Array to string conversion when retrieving outside function

Good day!
I have a problem here that I can't solve (last 5hrs).
here's my codes:
include 'assets\function\retrieveFunction.php';
$loadGradProgram = array();
$x = count(getCourseInfo());
for($i=0;$i<=$x;$i++){
$loadGradProgram[$i] = getCourseInfo();
}
echo $loadGradProgram[0];
getCourseInfo function
Solution 1:
function getCourseInfo(){
$getInfo = array();
include 'assets\database\connect.php';
$i = 0;
$x = 0;
$sql = "SELECT c.courseID, c.courseCode, c.courseTitle, m.description";
$sql .=" FROM tblcourse as c INNER JOIN tblcoursemajor as m ON c.courseid=m.courseID ORDER BY c.courseID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i] = $row;
$i++;
}
return $getInfo;
}
}
Result: Array to string conversion
Solution 2:
function getCourseInfo(){
$getInfo = array();
$loadInfo = array();
include 'assets\database\connect.php';
$i = 0;
$x = 0;
$sql = "SELECT c.courseID, c.courseCode, c.courseTitle, m.description";
$sql .=" FROM tblcourse as c INNER JOIN tblcoursemajor as m ON c.courseid=m.courseID ORDER BY c.courseID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i] = $row;
$i++;
}
$conn->close();
for($x,$x<=$i;$x++;){
$loadInfo[] = implode(',', $getInfo[$x]);
}
return $loadInfo;
}
}
Result: Still the same
and this line causing error: echo $loadGradProgram[0];
I use echo just to see if the query is working.
if you want a multi-dimmentional array like in w3c documentation, you do it like this :
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getInfo[$i][] = $row['courseID'];
$getInfo[$i][] = $row['courseCode'];
...
$i++;
}
return $getInfo;
then, if you want to diplay an information in the array you can do a foreach loop or a for loop like :
foreach($loadGradProgram as $key => $value) // here the key is useless
{
echo $value[0];
echo $value[1];
}
or directly like this :
echo $loadGradProgram[0][0];
echo $loadGradProgram[0][1];
echo $loadGradProgram[1][0];

Get an array of rows from a MySQL query?

I have this code...
$results_query = "SELECT * FROM profile WHERE string LIKE '%" . $search_deliminator . "%'";
$results_result = $database->query($results_query);
$result = mysql_fetch_array($results_result);
What I'm trying to do is pull all the rows in which the string column contains my search deliminator. Further, I would like to get the values from each column of the rows.
How would I pull the multidimensional array I need containing each row, and each value of each column within each row?
EDIT:
I'm looking to do something to this effect...
while ($row = mysql_fetch_assoc($results_result)) {
$result[] = $row;
}
Then echo each column like this...
foreach ($result as $row) {
echo $row["0"];
}
To get a flattened array of the result set, try this:
$result = array();
while ($row = mysql_fetch_assoc($results_result)) {
$result[$row['id']] = $row;
}
echo json_encode($result);
Also, you should look into either MySQLi or PDO to replace the (now deprecated) MySQL extension.
If you use PDO, you can use the fetchAll() method:
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
With mysql or mysqli, you use a loop:
$rows = array();
while ($row = $stmt->fetch_assoc()) {
$rows[] = $row;
}
try this
$i=0;
while ($row = mysql_fetch_assoc($results_result)) {
$result[$i]["column1"] = $row["column1"];
$result[$i]["column2"] = $row["column2"];
$i++;
}
To display the output use:
foreach ($result as $row) {
echo $row["column1"];
echo $row["column2"];
}

retrieve from all row and display it

$query = "SELECT * FROM main";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc()) {
$name= $row["name"];
$image = $row["image"];
}
}
then somewhere in my code I print it out using like echo $name; but I got only one result, which is the last row. I know I have to do foreach but what variable should I put?
foreach($result as $results) ? like this?
On every iteration, you reassign the values to $name and $image, causing it to show only the last value when it leaves the loop.
You can either echo them right away in the loop, or populate an array or an object with them, so they will be available later.
Example:
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = array('name'=>$row["name"], 'image'=>$row["image"]); // push into the array
}
var_dump($data); // it's all here now
And to echo the data later, one of the ways is foreach:
foreach($data as $row) {
echo "Name: ", $row['name'], "; Image: ", $row['image];
}
$query = "SELECT * FROM main";
$result = $db->query($query);
$row = $result->fetch_assoc();
foreach ($row as $rows) {
echo $rows['name'] ." ". $rows['image'];
}

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

Why does this query show only one result?

The query I have below will only show me one result even if there are multiple matching entries (completely or partially matching). How do I fix it so it will return all matching entries:
//$allowed is a variable from database.
$sql = "SELECT `users`.`full_name`, `taglines`.`name`, `users`.`user_id` FROM
`users` LEFT JOIN `taglines` ON `users`.`user_id` = `taglines`.`person_id`
WHERE ( `users`.`user_settings` = '$allowed' ) and ( `users`.`full_name`
LIKE '%$q%' ) LIMIT $startrow, 15";
$result = mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$num_rows1 = mysql_num_rows($result);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$person = htmlspecialchars($row['full_name']);
}
}
}
print $person;
Because your overwriting $person on each iteration.
Hold it in a $person[] array if your expecting more then one. Then loop through it with a foreach loop when you intend to output.
Not related but your also querying twice, you only need 1 $result = mysql_query($sql);
Update (Simple Outputting Example):
<?php
$person=array();
while($row = mysql_fetch_array($query)){
$person[] = array('full_name'=>$row['full_name'],
'email'=>$row['email'],
'somthing_else1'=>$row['some_other_column']);
}
//Then when you want to output:
foreach($person as $value){
echo '<p>Name:'.htmlentities($value['full_name']).'</p>';
echo '<p>Eamil:'.htmlentities($value['email']).'</p>';
echo '<p>FooBar:'.htmlentities($value['somthing_else1']).'</p>';
}
?>
Or an alternative way to is to build your output within the loop using concatenation.
<?php
$person='';
while($row = mysql_fetch_array($query)){
$person .= '<p>Name:'.$row['full_name'].'</p>';
$person .= '<p>Email:'.$row['email'].'</p>';
}
echo $person;
?>
Or just echo it.
<?php
while($row = mysql_fetch_array($query)){
echo '<p>Name:'.$row['full_name'].'</p>';
echo '<p>Email:'.$row['email'].'</p>';
}
?>

Categories