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.
Related
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've had a look through searches but there are so many differently worded question that I'm not sure which I should be looking for. Nor can I think how to word this to the best of my ability, but here goes:
I would like to take a mysqli_fetch_assoc() result and create an array for each row.
Let's say the result had two rows:
[0][0] = Cheese
[0][1] = 1
[1][0] = Milk
[1][1] = 2
How can I drop those into a newly created array let's say called $items?
What I'm hoping to achieve is:
$items = array(
array("Cheese",1),
array("Milk", 2)
);
The only code I have so far is this:
if($row = mysqli_fetch_assoc($q)) {
for($i=0;$i<$total;$i++) {
$items[$i][] = $row[$i];
}
}
I have not tried this, but I have this very unsettling feeling that it definitely won't be working.
would this not do it?
if($row = mysqli_fetch_assoc($q)) {
foreach($row as $r) {
$items[] = $r;
}
}
$new_arr = array();
while ($row = mysql_fetch_assoc($q))
{
foreach($row as $value){
$new_arr[][$value[0]] = $value[1];
}
}
I think this is what you need
while ($row = mysql_fetch_assoc($q))
{
$arr = [];
foreach ($row as $value)
$arr[] = $value;
$items[] = $arr;
}
var_dump($items);
mysqli_result::fetch_all()
"Returns an array of associative or numeric arrays holding result rows"
I think you're thinking too hard. A two dimensional array is already an array containing arrays. In your case, the result of fetch_all is precisely an array containing 'an array for each row'
If you're not intending to store the whole result set then you can do:
$rows[] = Array();
while ($row = mysqli_fetch_row() && $someCondition) $rows[] = $row;
but really you'd be better off to put a LIMIT on the query if possible.
I have a table that I need to find "top trusted builder" from, Trusts are separated by " ; ", So I need to pull all the data, explode the usernames, order and count them, and Im stuck on finally outputting the top username form the array, I have posted up the full segment of PHP, because im sure there has to be a much better way of doing this.
<?php
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$GMCB->setFetchMode(PDO::FETCH_ASSOC);
$buildersarray = array();
while($row = $GTB->fetch()) {
$allbuilders = explode(";", $row['builders']);
for($i = 0; $i < count($allbuilders); $i++)
{
$buildersarray[] = $allbuilders[$i];
}
}
echo "<pre>";
print_r(array_count_values(array_filter($buildersarray)));
echo "</pre>";
?>
Outputs
Array
(
[username1] => 4
[username2] => 1
[username3] => 1
)
You can return the array from the array_count_values command into a new array called $topbuilders, and then echo out the current (first) record:
$topbuilders = array_count_values(array_filter($buildersarray));
echo current(array_keys($topbuilders)).', Rank = '.current($topbuilders);
current() will return the first item in an associative array.
Instead of using array_count_values() it would be better to use the names as the key to a frequency array:
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$result = array();
while (($builders = $GTB->fetchColumn()) !== false) {
foreach (explode(";", $builders) as $builder) {
if (isset($result[$builder])) {
$result[$builder]++;
} else {
$result[$builder] = 1;
}
}
// sort descending based on numeric comparison
arsort($result, SORT_NUMERIC);
echo "Name = ", key($result), " Count = ", current($result), "\n";
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...
I am wondering how I can add a string variable to the current array. For example, I have an array called $finalarray. Then I have a loop that adds a value on every run. Basically:
$finalarray = $results_array + string;
A very basic structure. I am using this for MySQL so that I can retrieve the final array of the column.
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray = $finalarray + $results_array["column"];
}
Edit:
Currently using this code (still not working):
$query = “SELECT * FROM table”;
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["name"];
}
echo $finalarray;
The problem is that it just says "Array"
Thanks,
Kevin
Answer to your edited question:
You cannot use just a single echo to print the entire array contents. Instead
Use
var_dump($finalarray);
or
print_r($finalarray);
to print the array contents..
Use the [] notation. + is for unioning two arrays.
$array = array('foo');
$array[] = 'bar'.
// $array == array('foo', 'bar')
You can use the function array_push or [] notation:
array_push($array, 'hi');
$array[] = 'hi';
Take a look at this
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["column"];
}
// Add X to the end of the array
$finalarray[] = "X";
Codaddict is correct. You are looking to output the last element that was added to the array.
echo end($final_array);
That will move the array's pointer to the last element added to it and then output it. Since you're adding the elements to the array in this manner...
$finalarray[] = $results_array["name"];
The key for each of your elements will be sequential, 0,1,2,3...so on and so forth. Another less elegant solution to get the last element would be...
echo $final_array[count($final_array) - 1];
echo implode($finalarray);
Or with a custom join "glue"
echo implode(', ', $finalarray);