i am doing this select:
$result = $dbh->query("SELECT clicks FROM table WHERE click_date = '".$current_date."'");
$result->execute();
$array = array();
while ($user = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($array, $user['clicks'].",");
}
But this returns:
49572940
But it should be:
4,9,5,7,2,9,4,0
Anybody could help me to fix this problem?
Greetings!
Try this way:
<?php
$sql = "SELECT clicks FROM table WHERE click_date = '$current_date'";
foreach ($dbh->query($sql) as $row) {
$array[] = $row['clicks'];
}
//now echo and use implode
echo implode(", ", $array);
?>
because according to PHP Manual - PDO::query:
PDO::query — Executes an SQL statement, returning a result set as a
PDOStatement object
You should use fetchAll to get all the values and also if you want to execute a prepared statement you have to use prepare instead of query.
$sth = $dbh->prepare("SELECT clicks FROM table WHERE click_date = :current_date");
$sth->bindParam(':current_date', $current_date);
$sth->execute();
$result = $sth->fetchAll();
and after if you want a string with values separate by comma you can use implode as #jason suggested.
$str = implode(",", $result );
Related
So whenever I download data from my mysql database, and convert to a JSON array via PHP then display it, I get duplicated values.
I do understand why this is so, but is there any way to remove the numeric duplicates?:/
{"id":"1","0":"1","userId":"23","1":"23","message":"HELLO","2":HELLO"},
{"id":"2","0":"2","userId":"53","1":"53","message":"WOW","2":WOW"}
For PDO use PDO::FETCH_ASSOC flag after query execute
$sth = $dbh->prepare("SELECT col FROM table");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
And for mysql_* functions:
$query = "SELECT col FROM table";
$result = mysqli_query($connection, $query);
$output = array();
while($row = mysqli_fetch_assoc($result)){
$output[] = $row;
}
json_encode($output);
As you've asked, to remove it:
Loop through it, if key is numeric delete.
foreach($array as $key=>$var){
if(is_numeric($key)){
delete $array[$key];
}
}
I know how to use fetch_array instead of printf() function when expressing rows from database using mysqli bind function.
How can I use $row->mysqli_fetch_array and then use $row[0],$row[1] instead of using the printf() function every time I want to print something from database?
Returning an associative array from a prepared statement you can follow up the procedure like this as follows.
<?php
$category = $_POST['category'];
$sql = "select id, name from items where category = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param('s', $category);
if($stmt->execute())
{
$result = $stmt->get_result();
$a = $result->fetch_array(MYSQLI_ASSOC); // this does work :)
}
else
{
error_log ("Didn't work");
}
?>
You can use while loop for printing up the value over from the associative array.
while($a = $result->fetch_array(MYSQLI_ASSOC))
{
echo 'Id: '. $a['id'];
echo '<br>';
echo 'Name: '.$a['name'];
}
Output:
Id: 1
Name: Example
If I got your question correctly you can try:
$row=mysqli_fetch_array($result,MYSQLI_NUM);
foreach($row as $cell) {
echo "$cell";
}
Trying to put all results from oracle table into php variable using implode with this code but is not working.
What is wrong in here?
$sql = oci_parse($ora_con, "SELECT * FROM TABLE");
oci_execute($sql);
while (($row = oci_fetch_row($sql)) != false) {
echo $result = implode(',',(array)$row[0]);
}
And the result is: resul1result2result3result4
Instead of: result1, result2, result3
The problem here is that you're fetching a row at a time, then imploding a single-item, which ends up with no comma (as there's only one). You output that, then loop to the next result - which puts it in the output.
Instead, perhaps try the following, which constructs an array of the results, and then echos the imploded results:
$results = [];
while (($row = oci_fetch_row($sql)) != false) {
$results[] = $row[0];
}
echo implode(',', $results);
An alternative to choult's answer is to fetch all rows in the resultset directly using oci_fetch_all:
$sql = oci_parse($ora_con, 'SELECT * FROM TABLE');
oci_execute($sql);
oci_fetch_all($sql, $result, 0, -1, OCI_NUM);
echo implode(',', $result[0]);
A very nice person on this site helped me with the following script (and it worked a treat)
<?php
$db = new PDO('mysql:host=HOST;dbname=DATABASE', $user, $pass);
$stmt = $db->prepare('
SELECT
yeast,
rating,
description,
weblink,
image,
sideimage
FROM dowdb_yeast_selector
WHERE
fruit = :fruit
ORDER BY
rating DESC
');
$stmt->bindParam(':fruit',$_POST['fruit'],PDO::PARAM_STR,50);
$stmt->execute();
How do I just echo side image (not as part of a while loop)?
I think (?) I need something like echo '$row[sideimage]' // how simple am I
All of the examples I have looked at so far do not fit my needs :-(
Use PDO::fetchAll, for example;
$stmt->execute();
$arrResults = $stmt->fetchAll();
//$arrResults will be multidimensional
//This will echo the first sideimage
echo $arrResults[0]['sideimage'];
If you want to echo all values of sideimage (ie: all rows), you'd have to iterate through the results;
foreach($arrResults as $arrRow) {
echo $arrRow['sideimage'] . PHP_EOL;
}
Links
pdo::fetchAll
You should use loop pdo::fetch()
while($abc = $stmt->fetch())
{
print_r($abc);
}
If you don't want to use loop try pdo::fetchAll()
$data = $stm->fetchAll();
You could use FETCH_ASSOC
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo $res[0]['sideimage'];
or
foreach($res as $key=>$value) {
$image_val = $value['sideimage'];
}
I believe I am using the PDO fetch functions completely wrong. Here is what I am trying to do:
Query a row, get the results, use a helper function to process the results into an array.
Query
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$qr = $q->fetchAll(PDO::FETCH_ASSOC);
if ($qr->rowCount() > 0){
foreach($qr as $row){
$names[$row['id']] = buildArray($row);
}
return $names;
}
}
My custom array building function
function buildArray($row){
$usernames = array();
if(isset($row['id'])) $usernames['id'] = $row['id'];
if(isset($row['name'])) $usernames['name'] = $row['name'];
}
I'm actually getting exactly what I want from this, but when I echo inbetween I see that things are looping 3 times instead of once. I think I am misusing fetchAll.
Any help appreciated
If you're going to build a new array, there's not much point in having fetchAll() build an array. Write your own fetch() loop:
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$names = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$names[$row['id']] = $row;
}
return $names;
}
There's also no need for buildArray(), since $row is already the associative array you want.