For the last 1 1/2 days I've been trying to store 16 row id's into a string and separate each id with a comma. The array I am getting is from MySQL. The error I am getting is
implode() function:passed invalid arguments
$str=array();
$string="";
while($row = mysql_fetch_row($result))
{
$user_id=$row;
$str=$user_id;
foreach($str as $p=>$v){
comma($v);
}
}
function comma($v){
$string= implode(",",$v); echo $string;
}
Try something like this:
$ids = array();
while ($row = mysql_fetch_assoc($result))
{
$ids[] = $row["UserID"];
}
echo implode(", ", $ids);
Replace "UserID" with the columnname of the id in your table.
So: first you build the array, next you implode the array into a string.
There is my solution:
SELECT GROUP_CONCAT(UserID) as string FROM Users;
For this function the delimiter is ',' by default.
$query = 'SELECT id FROM your_table';
$rs = mysql_query($query);
$row = mysql_fetch_array($result);
return implode(',', $row);
the result 1,2,3...
Related
I have a csv string and need to select rows having corresponding id.
And need to do something specific if a row doesn't exist.
$str = '1,2,3,4,5,6,7,8,9,10,11,12';
$st = $db->query("select *
from arts
where id in (" . $str . ")
order by field (id, " . $str . ")");
$arr = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($arr as $el) {
// if ($el is missing) {echo 'the row is missing';} // how to do this?
else { ... }
}
The easiest option here, assuming you are stuck with the input CSV string, is to use FIND_IN_SET, something along these lines:
$sql = "SELECT id, FIND_IN_SET(id, :list) AS result FROM arts";
$str = "1,2,3,4,5,6,7,8,9,10,11,12";
$stmt = $db->prepare($sql);
$stmt->bindParam(':list', $str);
$stmt->execute();
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($arr as $el){
if ($el["result"] <= 0) {
echo "the row is missing for id " . $el["id"];
}
}
Rather than look at the records found, this code first keys the retrieved records on the id and then looks through the ID's you are looking for and if this record isn't found (using isset()) then process the not found part...
$arr = array_column($arr, null, "id");
$ids = explode(",", $str);
foreach($ids as $el){
if(!isset($arr[$el])) {
echo 'the row is missing';
} else{
echo 'the row is there';
}
}
I have a mysql table(request) here:
request:
r_id item_no
1 1
13 10
22 20
33 30
55 40
Now, I'm using php to take r_id out using mysql_fetch_array() and try to put mysql_fetch_array() result in to a string also split the string by comma.
<?php
include('config.php'); //connect to mysql
function f(){
$sql = "SELECT r_id FROM `request` ";
$result=mysql_query($sql);
$string = '';
$i = 0;
while ($row = mysql_fetch_array($result)) {
$string .= $row[$i];
}
$newstring = implode(", ", preg_split("/[\0-9]+/", $string));
return $newstring ;
}
$get=f();
echo $get;
?>
But I cannot get the right string form my php code.
I want to get the string like
1,13,22,33,55
How can I fix the problem?
You don't need to split that and implode, just do this:
while ($row = mysql_fetch_array($result)) {
$string .= $row[$i].',';// append comma after each value you append to the string
}
return substr($string,0,-1);// cut off the trailing comma from the final string
<?php
include('config.php'); //connect to mysql
function f(){
$sql = "SELECT GROUP_CONCAT(r_ID) FROM `request` ";
$result=mysql_query($sql);
return $result ;
}
$get=f();
echo $get;
?>
Try my updated answer:
$sql = "SELECT r_id FROM `request` ";
$result=mysql_query($sql);
$string = '';
$i = 0;
while ($row = mysql_fetch_array($result)) {
$string .= $row[$i].",";
}
return $string ;
}
$array = array();
while(...){
$array = $row[$i]; //first you need array
}
$string = implode(",",$array); //now you have your string
In my database table there is a column named 'marks' . it contains values like 50,55,67,88,...
Now I need to read this values one by one like - first 50, then 55 and so on. How is it possible using php ?
include("db_connect.php");
$result = mysql_query("SELECT * FROM students ",$con);
while($rows = mysql_fetch_array($result))
{
$mark1=$rows['marks'];//what will do here
$mark2=$rows['marks']; //should get value 55 and so on
}
If your values are comma separated then explode the field.
http://php.net/manual/en/function.explode.php
include("db_connect.php");
$result = mysql_query("SELECT * FROM students", $con);
while($rows = mysql_fetch_array($result)) {
$mark=explode(',', $rows['marks']);//what will do here
foreach($mark as $out) {
echo $out;
}
}
Explode the data from the database. Use the explode function.
Access using indexes
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
$mark1 = $exp[0]; //result is 50
$mark2 = $exp[1]; //result is 55
$mark3 = $exp[3]; //result is 67
}
Or loop using foreach
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
foreach($exp as $mark) {
echo $mark;
}
}
If that row contains ,, the just use explode():
while($rows = mysql_fetch_assoc($result)) {
$mark1 = explode(',', $rows['marks']); // should contain the comma separated values
// in array form
// then loop again
foreach($mark1 as $mark_piece) {
// do something here
}
}
You should use the explode function
$marks = explode(",", $rows['marks']);
foreach($marks as $mark){
//your code to do something with the mark.
}
N.B. explode() function breaks the string into array, it accepts three arguments, first one is the delimiter that specifies where to break the string, second one is the string that needs splitting, and third one is not mandatory but it tells how many array to return.
$str_to_exploade = 'This,string,needs,some,exploiting';
$explode_string = explode(',', $str_to_exploade);
echo '<pre>';
print_r($explode_string);
echo $explode_string[0].'<br/>';
echo $explode_string[1];
More about explode() go to : http://php.net/manual/en/function.explode.php
I'm trying to put an array into a query but I doens't work. I'm tying it with implode() but then it gives me " Array to string conversion in ... on line 26". Why? With json_encode it worked out ...
Thanks for your help!
$sql = mysql_query("SELECT follows
FROM follow
WHERE follower LIKE '".$id."'") or die (mysql_error());
if(mysql_num_rows($sql) < 1){
echo "<br/>";
echo "Follow someone";
} else {
//Put all the id's of the users the user is following in an array.
$i = 0;
$user_follows = array();
while ( $row = mysql_fetch_assoc($sql) )
{
$user_follows[$i] = $row;
$i++;
}
$user_follows = implode(" , ", $user_follows);
echo $user_follows;
}
The second argument to implode must be an array of strings. But you're doing:
$user_follows[$i] = $row;
Since $row is an array, you're making an array of arrays (a 2-dimensional array), not an array of strings. That should be:
$user_follows[] = $row['follows'];
You don't need the $i variable, assigning to $array[] appends a new element to the array.
I want to store ids in database like this 1,2,3,4,5 in one field from a while loop.
how can i do this.
I am trying this way.
$array = array();
while($row=mysqli_fetch_assoc($result)){
$array[] = array($row['id']);
}
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$array')");
print_r($array);
This is showing error Array to string conversion and value as Array is inserted in database.
Please see and suggest any possible way to do this.
Thanks.
Create another table and insert 5 rows into it.
entity_id | ids
1 1
1 2
1 3
1 4
1 5
that's the only proper way of doing such things
However, if it's really a temp table, there is probably a way to avoid these inserts at all.
You can use either serialize or json_encode:
$data = serialize($array);
// ...or...
$data = json_encode($array);
If the array just contains plain numbers you can also use implode:
$data = implode(',', $array);
$arrays = array();
while($row=mysqli_fetch_assoc($result)){
$arrays[] = $row['id'];
}
$arr_str = implode(",", $arrays);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$arr_str')");
//print_r($array);
Detailed information about implode can be found here.
Use the implode() function:
$to_insert = implode(',', $array);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$to_insert')");
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES(".join(',', $array).")");
Try:
$ids = join(',',$array);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$ids')");
Please use implode function before insert into database :-
Here is a example :-
$array = array(1,2,3);
$comma_separated = implode(",", $array);
echo $comma_separated;
Output :-
1,2,3
In your case :-
$array = array();
while($row=mysqli_fetch_assoc($result)){
$array[] = array($row['id']);
}
$comma_separated = implode(",", $array);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$comma_separated')");
print_r($array);
Set the field type varchar(255) and do this with php
$array = array();
$value = serialize($array);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$value')");
print_r($array);
To retrieve the value you should unserialize the column
$data = unserialize($result['temp']);
Here result is associative array. $data is an array you dont have to implode or explode or json_encode or json_decode