This question already has an answer here:
making an array from database [closed]
(1 answer)
Closed 9 years ago.
i have this script and im having a problem passing this array to a string with commas.
i want it to be a string so i can insert it as a variable inside another query in the select...where... IN($variable);
i tried the implode and it dont echo the ids as a string it echoes Array.
error_reporting(E_ALL);
mysql_connect("localhost", "root", "root");
mysql_select_db("wall");
$sql = "select id from table where id=1";
$result = mysql_query( $sql);
$myArray='';
while($row = mysql_fetch_array($result)){
$popurl = $row['id'];
$myArray[] = $popurl;
}
echo "<pre>";
print_r($myArray);
Try this code:
$myArray= array() ; //Here you must declare it as array
while($row = mysql_fetch_array($result)){
$popurl = $row['id'];
$myArray[] = $popurl;
}
$string = "'" . implode("', '", $myArray) . "'" ;
//Will make ready string like 'data','data2', 'data3'
Related
This question already has answers here:
MySQL Results as comma separated list
(4 answers)
Comma separated string of selected values in MySQL
(10 answers)
Just need a comma separated list from PHP/MySQL query [duplicate]
(5 answers)
Closed 2 years ago.
My goal: insert into a variable an array of items coming from a query and then print it
steps:
launch the query
do something with php
print the variable $report = 'this is your list: $list';
tried this:
$myquery = mysqli_query($dbconnection, "SELECT ...");
while($row = mysqli_fetch_assoc($myquery)) {
$my_array = $row['field'];
echo "$my_array, "; /* here I've the full list*/
}
$report = 'this is your list:' .$my_array. '.';
echo "$report"; /*I've only one item and not all the list*/
Your first echo is called several times because it is in the loop.
In every iteration you are replacing your content of $my_array.
Instead, try to attach it:
$my_array[] = $row['field'];
For more information see https://www.php.net/manual/de/language.types.array.php
This is normal.
Your while loop doing a "step" for each row found with your query.
You assigned $my_array as the "column" with the name field.
So at the end of the while loop, you'll get only the last column field of the last row.
Instead, try this
$myquery = mysqli_query($dbconnection, "SELECT ...");
$myWholeList = ''; // HERE
while($row = mysqli_fetch_assoc($myquery)) {
$my_array = $row['field'];
echo "$my_array, ";
$myWholeList .= '$my_array '; // HERE
}
$report = 'this is your list:' .$my_array. '.';
echo "$myWholeList"; // HERE
I've done a string concatenation, but you can do it with array and print_r() function. Have a look on this thread to see how to append data to an array.
mysqli_fetch_array while loop columns
EDIT:
Based on #isabella 's comment, she wants to display 7 items of array.
Two way :
Use print_r() or var_dump() which is the best to display an array (without taking care about rendering)
Add to $myWholeList variable each item.
e.g.
$myquery = mysqli_query($dbconnection, "SELECT ...");
$myWholeList = ''; // HERE
while($row = mysqli_fetch_assoc($myquery)) {
$my_array = $row['field'];
echo "$my_array, ";
// HERE
foreach($row as $field) {
$myWholeList .= $field . ' ';
}
$myWholeList .= '<br>'; // NEW LINE
}
$report = 'this is your list:' .$my_array. '.';
echo "$myWholeList"; // HERE
I have made MySQL database with three columns tags_id,tags,user_id, it must give out all the tags with respect to the user_id given.
eg: for this link:"http://allwaysready.16mb.com/Cuboid/tagsTest.php?user_id[]=7"
Output is:
{"result":[{"tags":"Pascol"},{"tags":"PHP"},{"tags":"Python"}]}
But I need my result to be in a sing string like this:
{"result":[{"tags":"Pascol","PHP",","Python"}]}
It should not be in array i want it in a single string.
Here is my php code :
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$user_id = $_GET['user_id'];
require_once('dbConnect.php');
$user_tags = array();
foreach ($_REQUEST['user_id'] as $key => $val) {
$user_tags[$key] = filter_var($val, FILTER_SANITIZE_STRING);
}
$user_ids = "'" . implode("','", $user_tags) . "'";
$sql = "SELECT * FROM user_tags WHERE user_id IN ({$user_ids})";
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"tags"=>$row['tags']
));
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
}
what should i change in my code.?
please help me guys thank you.
Your array_push mean
Push to your array new element with $key => $value
So solution in this case is remove array_push and try
$result['tags'][] = $row['tags'];
im retrieving some data in my database table and than convert to json, but i need to create a array with this structire in my php loop
["postcode"=>"townName"...]
but instead is giving me
["postcode=>townName"...]
My code:
$sql = "SELECT * FROM uk_postcodes";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$dname_list[] = $row['postcode']."=>".$row['town'];
}
echo json_encode($dname_list);
In that line:
$dname_list[] = $row['postcode']."=>".$row['town'];
You're creating a string with "=>" in the middle (see string concatenation). You should specify the key of the array to be the postcode field, and the value - town field. Just change that line to:
$dname_list[$row['postcode']] = $row['town'];
http://php.net/manual/en/language.types.array.php
This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
I'm trying to query the DB with mysqli and then fetch the result, but it's throwing an Object of class could not be converted to a string error.
Here's what I am trying to accomplish:
<?php
include ('conn.php');
$query= "select value from the_table where item = 'url'";
$result = mysqli_query($conn, $query);
?>
And then I am trying to populate a link with the $result:
This is the Link to the URL
I saw this post: PHP and MySQL error: Object of class mysqli_result could not be converted to string
So, I tried to format the echo with echo $result->fetch_object()->url;, but that didn't work.
I'm not sure if I have to fetch the result and then throw it into a look with a mysqli_fetch_array() and if so, how do I get it to populate that the value outside of the loop?
Assuming that $db is your database connection link you can perform the query:
$result = mysqli_query($db, 'select name from fruits');
Then you can get name using procedural style:
echo mysqli_fetch_object($result)->name;
Or object style:
echo $result->fetch_object()->name;
In your code you're trying to output url property which is not defined - as we can see in your query.
Try some thing like this:-
$query= "select value from the_table where item = 'url'";
$result = mysqli_query($conn, $query) or die ("Couldn't execute query.");
// use returned data
while($row = mysqli_fetch_assoc($result))
{
echo $row['value'];
}
OR
while ( $row = mysqli_fetch_assoc( $result ) )
{
foreach ($row as $key => $value)
{
print ($row . " = " . $value . "\n");
}
print("================");
}
I have an app that records months and years by one CSV entry, i.e. db column named answer1 is jan,2008 and column answer2 is feb,2013. I want to use a specific month (jan) in html but it only gives me the last array data.
<?php
foreach ($row as $colName => $colValue )
{
if($colName === answer1 || $colName === answer2)
{
//break apart date data
$myArray = explode(',', $colValue);
echo '<div id=" ' .$colName . $myArray[0] . ' ">test</div> ';//this works
};
};
?>
I'd like something like this in another php block later in the doc.
<?php echo '<div id=" '.$colName[answer2] . $myArray[0] . ' ">test</div> ';?>
This is probably a lot easier. We're exploding (or pulling two substrings) from the original columns in MySQL before we get to PHP. Then you can use them however you would like:
$query = "SELECT SUBSTRING_INDEX(answer1,',',1) as a1_month,
SUBSTRING_INDEX(answer1,',',-1) as a1_year,
SUBSTRING_INDEX(answer2,',',1) as a2_month,
SUBSTRING_INDEX(answer2,',',-1) as a2_year from my_table";
$result = mysqli_query($query);
$answers = array();
$x = 0;
while ($row = mysqli_fetch_array($result)){
$answers[$x]['answer1_year'] = $row['a1_year'];
$answers[$x]['answer1_month'] = $row['a1_month'];
$answers[$x]['answer2_year'] = $row['a2_year'];
$answers[$x]['answer2_month'] = $row['a2_month'];
$x++;
}
print_r($answers);
If for some reason you still want the concatenated strings you can do this:
$answer1 = $answers[0]['answer1_month'].','.$answers[0]['answer1_year'];
$answer2 = $answers[0]['answer2_month'].','.$answers[0]['answer2_year'];