I'm trying to use implode() in a script to return the result of an SQL query as a string so I can insert it into another table, however whenever I manage to get the implode to return anything it will only return a single result, even though the query returns more than one result.
Note: my PHP is not the strongest and I am using pre-existing code and reworking it, which is why a lot of the code will look like it's meant for a JSON API.
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Events Scheduled!";
$response["events"] = array();
foreach ($rows as $row) {
$post = array();
$post["id"] = $row["id"];
$post["message"] = $row["message"];
$post["pin"] = $row["pin"];
array_push($response["events"], $post);
$matstring=implode("', '",$post);
}
}
When echo'd out I get:
3', 'Test to check multiple entries are in array for when the check is made, this should be seen.', '12345
imploding $response['events'] returns "Array, Array" and everything else I have tried returns nothing. Where should I look to get the other entry?
I think what are you want is like this:
$str = "'".implode(",'", $post)."'";
echo $str;
Related
I have a PHP script that queries my database, I then loop through the results, convert to JSON and use this to populate some charts using Chart.js
Currently my query only returns 2 columns (month and mitigator_deployed) which is fine, but in reality my query is going to be returning many many columns and then I'd like to select which results I convert to JSON and populate in my charts.
I'm pretty sure that looping through each column one by one and then storing into an array is not the most efficient way to do this!
Here is my current code. (BTW I know I should be using prepared statements!)
//DB CONNECTION HERE!
$data_sql = file_get_contents('data/sql.sql');
$data_results = mysqli_query($conn_1, $data_sql);
if($data_results === false) {
echo mysqli_error($conn_1);
} else {
$rows = mysqli_fetch_all($data_results, MYSQLI_ASSOC);
}
$month = [];
$value = [];
foreach($rows as $row) {
$month[] = $row['month'];
$value[] = $row['mitigator_deployed'];
}
$month_data = json_encode($month, JSON_PRETTY_PRINT);
$value_data = json_encode($value, JSON_PRETTY_PRINT);
//REMOVE DOUBLE QUOTES FROM NUMBERS
$newdata = str_replace('"', '', $value_data);
?>
<div><?php pie_chart(1, 500, $newdata, $month_data); ?></div>
Ideally I'd like to retrieve everything and then choose which column in my json_decode function, like so;
$column = json_encode($row['my_column'], JSON_PRETTY_PRINT);
Is there a more efficient way of doing this?
Thanks
Use array_column() to get specific columns from a an array into new arrays:
$rows = mysqli_fetch_all($data_results, MYSQLI_ASSOC);
$month = array_column($rows, 'month');
$value = array_column($rows, 'mitigator_deployed');
// just add more if you need to
I can't seem to find a way to save all rows from odbc_exec to an array. I found php_fetch_array, but that only fetches one row at a time, requiring me to iterate through all rows to put it into an array. Is there a more concise way to do this?
Tried
`
$myArray = array();
while (odbc_fetch_row($result)) {
$myArray[odbc_result($result,1)] = odbc_result($result,2);
}`
and also
`
$myArray = array();
while ($myRow = odbc_fetch_row($result)) {
$myArray[$myRow['id']] = $myRow['name'];
}`
but $myArray is still empty.
$sql = mysql_query("SELECT * FROM table WHERE user='$user'" );
while($data=mysql_fetch_array($sql)){
echo $data['user']; //this is fine
}
echo $data['user'];
$data=mysql_fetch_array($sql);
echo $data['user'];
The last two echos are empty?
I need to have an array outside of the loop that is equivalent to the 'last' loop cycle.
The while loop keeps fetching data, until there is no more data and therefore false is returned by mysql_fetch_array. This last value, false, is still in $data after the loop has ended, but simply printing it using echo, won't print anything you can see. The same goes for the next call of mysql_fetch_array and echo. You can check this by doing a var_dump of the $data variable. This will show you that it contains the boolean false.
If you want to be able to use the data after the loop has ended, you can save all the data you fetch into one big array. That might be a bad option though if you're fetching a lot of data, but from there you should be able to change it yourself so you can save and use the useful data. To store all the data in an array, change the loop into this:
$alldata = array();
while($data=mysql_fetch_array($sql))
{
echo $data['user'];
$alldata[] = $data;
}
You can then for example iterate over $alldata to go over the results again.
Update: In your last comment you said you want to access the last record that was fetched. You can do that like this:
$lastdata = array();
while($data=mysql_fetch_array($sql))
{
echo $data['user'];
$lastdata = $data;
}
$lastdata will then contain the last record in your result.
Because of the following:
while($data = mysql_fetch_array($sql)) {
// mysql_fetch_array returned something 'not false' and this value
// is assigned to $daat
}
// mysql_fetch_array() returned false, because there are no more rows
// false is assigned to $data, and because the statement within while(...)
// isn't true anymore the loop is stopped.
Use
$data = mysql_fetch_array($sql);
if (!$data) {
echo "User don't exists";
}
for example to handle this situation
I want to add a bit more information to a json object before sending it back to my app.
$sql = "SELECT * FROM users WHERE repo=?";
$q=$dbh->prepare($sql);
$q->execute(array($repo));
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res['isnew']="1"; //this part isn't working
echo '{"items":'. json_encode($res) .'}';
The PDO query returns a result set like this when I echo($res)
Array{"items":[{"uid":"10","repo":"bnef"}]}
then it gets encoded back to jquery- echo '{"items":'. json_encode($res) .'}';
giving me
{"items":[{"uid":"10","repo":"bnef}]}
I'd like to add "isnew":"1" to that but when I try
$res['isnew']="1"; or array_merge I end up with
{"items":{"0":{"uid":"10","repo":"bnef"},"isnew":"1"}}
which doesn't work. I need
{"items":[{"uid":"10","repo":"bnef, "isnew":"1"}]}
Am I misguide in try to do this?
I misread your question and got confused on the code... you shoudl incat be dealign with an array initially try the following:
$sql = "SELECT * FROM users WHERE repo=?";
$q=$dbh->prepare($sql);
$q->execute(array($repo));
$items = $q->fetchAll(PDO::FETCH_OBJ);
// you actually wnt isnew as a property of each row
// so you need to loop over the results
foreach($items as $key => $item){
$item->isnew = 1;
}
echo json_encode(array(
'items' => $items
));
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res['isnew']="1"; //this part isn't working
Its not working because you used FETCH_OBJ instead of FETCH_ASSOC so youre wokring with an StdObject instance not an array. In that case you need to use -> to assign:
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res->isnew = "1";
Alternatively you could fetch as an associative array:
$res = $q->fetchAll(PDO::FETCH_ASSOC);
$res['isnew']="1"; //this will work now
Additionalyl i wouldnt try to manipulate the JSON serialized string. I would doo all modifications natively:
$items = array(
'items' => $res
);
echo json_encode($items);
I have a typical database query:
$query = mysql_query('SELECT titulo,referencia FROM cursos WHERE tipo=1 AND estado=1');
and I can convert it in an array and print the data:
while ($results=mysql_fetch_array($query)): ?>
echo $results['referencia'];
// and so...
endwhile;
but in some cases I need to print the same data in another part of the web page, but the $results array seems to be empty (I use var_dump($results) and I get bool(false)). I plan to use what I learned reading Create PHP array from MySQL column, but not supposed to mysql_fetch_array() creates an array? So, what happen?
Tae, the reason that your $result is false at the end of the while loop is that mysql_fetch_array returns false when it reaches the end of the query set. (See the PHP Docs on the subject) When you reach the end of the query set $results is set to false and the while loop is exited. If you want to save the arrays (database row results) for later, then do as Chacha102 suggests and store each row as it is pulled from the database.
$data = array();
while($results = mysql_fetch_array($query)) {
$data[] = $results;
}
foreach ($data as $result_row) {
echo $result_row['referencia'];
... etc.
}
Try this
while($results = mysql_fetch_array($query))
{
$data[] = $results;
}
Now, all of your results are in $data, and you can do whatever you want from there.
As Anthony said, you might want to make sure that data is actually being retrieved from the query. Check if any results are being returned by echo mysql_num_rows($query). That should give you the number of rows you got