How to convert an array to a string - php

What I want is to convert an array to a string so I can display it on my websites. I made a query to select the values id, title, date, auteur. When i use my function I made for this, I get the following error:
Notice: Array to string conversion in /Applications/MAMP/htdocs/beheer/index.php on line 444
Array.
The function is as following:
<?php
include ('connect/connect.php');
function getListContentMain() {
global $con;
$dbname = 'content';
mysqli_select_db($con,$dbname);
$q = "SELECT * FROM main LIMIT 5";
$result = mysqli_query($con,$q);
$ListContentMainData = array();
while($row = mysqli_fetch_array($result)) {
echo $row['id'];
echo $row['title'];
echo $row['date'];
echo $row['auteur'];
}
$ListContentMainData[] = $row;
return $ListContentMainData;
}
?>

implode it up
return implode(' ',$ListContentMainData);
You are returning an array but you are trying to print it as a normal string , so in that case you need to implode it (array) and convert it to a string.
Rewrite like..
$ListContentMainData = array();
while($row = mysqli_fetch_array($result)) {
echo $row['id'];
echo $row['title'];
echo $row['date'];
echo $row['auteur'];
$ListContentMainData[]=$row['id'];
$ListContentMainData[]=$row['title'];
$ListContentMainData[]=$row['date'];
$ListContentMainData[]=$row['auteur'];
}
return implode(' ',$ListContentMainData);

This will make an array of strings, one for each row in the table with columns separated by a space (you could change that in the implode statement).
function getListContentMain() {
global $con;
$dbname = 'content';
mysqli_select_db($con,$dbname);
$q = "SELECT * FROM main LIMIT 5";
$result = mysqli_query($con,$q);
$ListContentMainData = array();
while($row = mysqli_fetch_array($result)) {
echo $row['id'];
echo $row['title'];
echo $row['date'];
echo $row['auteur'];
array_push($ListContentMainData, implode(' ', $row));
}
return $ListContentMainData;
}

Related

Query dont want to show all related post from table

I try to retrive all rows related to the specific category(continent table) but it only shows one and not all.
<?php
$townid = $_GET['id'];
$query = "SELECT * FROM towns INNER JOIN continents ON towns.catid = continents.id WHERE continents.id = '$townid'";
$row = mysqli_fetch_assoc(mysqli_query($link, $query));
// The category/Continent
echo '<h1>';
echo $row['catname'];
echo '</h1>';
//The post name/Town name
echo $row['title'];
?>
You need to call mysqli_fetch_assoc() in a loop.
$result = mysqli_query($link, $query);
$first = true;
while ($row = mysqli_fetch_assoc($result)) {
if ($first) { // Only show the category header once.
// The category/Continent
echo '<h1>';
echo $row['catname'];
echo '</h1>';
$first = false;
}
//The post name/Town name
echo $row['title'];
}
You can do something like:
<?php
$townid = $_GET['id'];
$query = "SELECT * FROM towns INNER JOIN continents ON towns.catid = continents.id WHERE continents.id = '$townid'";
$rows = mysqli_fetch_all(mysqli_query($link, $query), MYSQLI_ASSOC);
// The category/Continent
foreach ($rows as $row) {
echo '<h1>';
echo $row['catname'];
echo '</h1>';
//The post name/Town name
echo $row['title'];
}
?>
On another note, its better to parameterised your query since you are getting the $townid from a GET params.
This is how to do it in PHP https://www.php.net/manual/en/mysqli-stmt.bind-param.php

implode output does not gives proper output

This shows all the elements from an array in a string but without a separator. I used ',' as a separator in this code. And it does not work. How can i separate them with separator.
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Database Connection failed.".mysql_error());
}
$db = mysql_select_db("test1",$con);
if(!$db)
{
die("Database selection failed.".mysql_error());
}
$query = "select * from menu limit 10";
$result = mysql_query($query,$con);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
//$menu_name = $row['m_name'];
//$menu_image = $row['m_image'];
$menu_name = array($row['m_name']);
$menu_image = array($row['m_image']);
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
}
if(!$result)
{
echo mysql_error;
}
?>
you are storing array into variable . so if you will use imploade on an variable it will not show the result so best way is to store your result into an array and then use implode .
Don't use depricated mysql_* function use mysqli_* or pdo
instead
$menu_image=array(); // start array to store
$menu_name=array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name']; // store menu name
$menu_image[] = $row['m_image']; // store menu image
}
echo implode(',',$menu_name); // finaly use implode
You can try this:
$menu_name[];
$menu_image[];
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$menu_name[] = $row['m_name']; // I change your $menu_name into an array so that when you fetch $row['m_name'] it returns an array
$menu_image[] = $row['m_image']; //same thing
}
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
try this in place of your while loop
$menu_name = array();
$menu_image = array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name'];
$menu_image[] = $row['m_image'];
}
echo implode(',',$menu_name);

How to contain a while loop in a variable

I have the following code:
<?php
if(isset($_POST['indexSearchSubmit']))
{
foreach($_POST['industryList'] as $selected)
{
$_POST['industryList'] = $selected;
$locationListResults = $_POST['locationList'];
$results = mysqli_query($con,"SELECT * FROM currentListings WHERE location = '$locationListResults' AND industry = '$selected'");
while($row = mysqli_fetch_array($results))
{
echo $row['industry'];
echo $row['location'];
echo $row['title'];
echo $row['description'];
}
}
mysqli_close($con);
}
?>
Could anyone tell me how I would go about storing the echo part into a variable so I can then display it as and where I want in other parts of the site?
If I remove the echo and instead store $row as a variable when I echo that variable it only outputs once and doesn't run the loop.
You should use mysqli_fetch_all for this. The result will be an array where each element is a row and each row is an associative array with the same keys as row in your example
$data = mysqli_fetch_all($result);
$data[0]["industry"]; //Data in the first row
You can then loop over $data to output it any place on your page.
put in array,
$list = array();
while($row = mysqli_fetch_array($results))
{
$list[] = $row;
}
you may try this
$arrayList = array();
while($row = mysqli_featch_array($results)){
$arrayList[] = $row;
}
print_r($arrayList);
Put all the values in an array
$rows = array();
$x = 0;
while($row = mysqli_fetch_array($results))
{
$rows[$x]['industry'] = $row['industry'];
$rows[$x]['location'] = $row['location'];
$rows[$x]['title'] = $row['title'];
$rows[$x]['description'] = $row['description'];
$x++;
}
return $rows;
Then you can use $rows as an array.
foreach($rows as $v){
echo $v['industry']." ".$v['location']."<br />";
echo $v['title']." ".$v['description']."<br />";
}

mysqli_fetch_array reading result as null?

Any idea why this is showing a result of null? I'm guessing it has to do with where I put $link before I did the query, but it has to be done that way, correct?
function getcatposts($cat_id) {
$qc = #mysqli_query($link, "SELECT * FROM topics WHERE topic_cat='$cat_id'");
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
}
$qc2 = #mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
}
Updated code:
function getcatposts($cat_id) {
$link = mysqli_connect("localhost", "lunar_lunar", "", "lunar_users");
$qc = mysqli_query($link, "SELECT * FROM topics WHERE topic_cat='$cat_id'");
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
}
echo $cat_name;
echo '<br />';
echo $topic_title;
echo '<br />';
echo $topic_id;
}
New issue is that its displaying like this:
http://gyazo.com/43e8a91b9e0cf4f5e413536907891dcf.png
When the DB looks like this:
http://gyazo.com/1ead8bd0f150838dae3ee4a476419679.png
It should be displaying all three of them and this is a function meaning it will keep redoing all the code until it can't query anymore data. Any ideas?
The problem here is that you're trying to echo the values outside your loop. The variables inside the loop will get overwritten on each iteration and at the end of looping, the variable will hold the value of the last iteration.
If you want to display all the values, move the echo statement inside your loop, like so:
while($row = mysqli_fetch_array($qc))
{
$topic_title = $row['topic_subject'];
$topic_id = $row['topic_id'];
echo $topic_title.'<br/>';
echo $topic_id.'<br/>';
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2))
{
$cat_name = $row2['cat_name'];
echo $cat_name.'<br/>';
}
If you care about the order, you could store the titles, ids and cat_names in arrays like so:
while($row = mysqli_fetch_array($qc))
{
$topic_title[] =$row['topic_subject'];
$topic_id[] = $row['topic_id'];
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2))
{
$cat_name[] =$row2['cat_name'];
}
And then loop through them:
for ($i=0; $i < count($topic_id); $i++) {
if( isset($topic_id[$i], $topic_title[$i], $cat_name[$i]) )
{
echo $cat_name[$i].'<br/>';
echo $topic_title[$i].'<br/>';
echo $topic_id[$i].'<br/>';
}
}
Your function displays only one result because your echo is outside the while loop...
Put the Echo statements inside the loop, or you will print only the last result!
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
echo $topic_title;
echo '<br />';
echo $topic_id;
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
echo $cat_name;
echo '<br />';
}

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

Categories