PDO query using dynamic parameter (arrays) - php

I am working out a function that is meant to query to the database using PDO. I am working with arrays to execute. I am getting error HY093. Below is my code
//my function
function test_function($statement,$data,$connect)
{
$gg = implode(',',$data);
$sth = $connect->prepare($statement);
$sth ->execute(array($gg));
$r_result = $sth->fetch();
$show_result = $r_result['0'];
return $show_result;
}
$datas = array("':ids' => 1"," ':stats' => 1");
$showsh = test_function("SELECT COUNT(*) FROM table WHERE col1 > :ids AND col2 =
:stats",$datas,$con);
echo $showsh;
Any guidance will be helpful.

Your first error is in the creation of the array. You're creating an array with 2 strings, instead of an array with 2 key/value pairs. It should be this:
$datas = array(':ids' => 1,':stats' => 1);
Next up is inside of the function. You're turning the $data variable into a string, then passing that inside of an array into your query. Forget all that, and just pass $data into your execute.
$sth = $connect->prepare($statement);
$sth ->execute($data);

Refactor $datas to [":ids" => 1, ":stats" => 1]
Then edit the function:
function test_function($statement,$data,$connect)
{
$sth = $connect->prepare($statement);
$sth ->execute($data);
$r_result = $sth->fetch();
$show_result = $r_result['0'];
return $show_result;
}
If you must not change the $datas format, you must refactor it within the code. Something like:
$correctData = [];
foreach ($datas as $item) {
$elements = explode("=>", $item);
$key = preg_replace("/\s\'/", "", $elements[0]);
$element = preg_replace("/\s\'/", "", $elements[1]);
$correctData[] = [$key => $element];
}
$showsh = test_function("SELECT COUNT(*) FROM table WHERE col1 > :ids AND col2 =
:stats",$correctData,$con);
Edited: preg_replace("(/\s)(\')/", "",... to preg_replace("/\s\'/", "",...

Thank you Aynber for your answer. I am posting an answer using the ? instead of the :. In this answer I am not using the associative array.
function test_function($statement,$data,$connect)
{
$sth = $connect->prepare($statement);
$sth ->execute($data);
$r_result = $sth->fetch();
$show_result = $r_result['0'];
return $show_result;
}
$datas = array(1,1);
$showsh = test_function("SELECT COUNT(*) FROM table WHERE col1 >? AND col2 = ?",$datas,$con);
echo $showsh;

Related

Php array from sql result

How can i create an array from the result? I would like to use the array in a mysql IN() query.
//$array = array();
$get_subscategoria = mysqli_query($kapcs, "SELECT kat_id FROM termek_kategoria WHERE kat_parent = '$id'");
if(mysqli_num_rows($get_subscategoria) > 0 )
{
while($sub_kat = mysqli_fetch_array($get_subscategoria))
{
echo $sub_kat['kat_id'];
//$array[] = $sub_kat;
}
}
//print_r( $array );
Now, this code gives back 4 row ID, that works okay. I would like an array with these ID-s, like 1,2,3,4.
Instead of:
while($sub_kat = mysqli_fetch_array($get_subscategoria))
{
echo $sub_kat['kat_id'];
//$array[] = $sub_kat;
}
use:
$array = mysqli_fetch_assoc($get_subscategoria);
while($sub_kat = mysqli_fetch_array($get_subscategoria))
{
$array[] = $sub_kat['kat_id'];
}
echo implode(",",$array);
it give a result like 1,2,3,4
For MySQL, also you can use group_concat, only gives you one record:
SELECT GROUP_CONCAT(kat_id) AS kat_id
FROM termek_kategoria
WHERE kat_parent = '$id'
GROUP BY kat_parent

How to add a data to each JSON object PHP

I'm getting posts details from 'postsTable' with php and encoding it in JSON Like this way
$result_json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($result_json);
each post has a unique ID
Then I have another table called 'postsLikes' I want to see how many Likes the post have using mysqli_num_rows()
But my question is how can I add the data it returns to each object in Encoded JSON ?
$query_checkup = "SELECT * FROM postsTable WHERE Post_AgeFrom < $age AND $age < Post_AgeTo AND Post_Reviewed = 1";
$result=mysqli_query($con, $query_checkup);
$result_json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo "{\"result\":";
echo json_encode($result_json);
echo "}";
You should append extra data to your array before encoding to json.
foreach ($result_json as $key => $result) {
$result_json[$key]['likes'] = getLikes();
}
echo json_encode($result_json);
And you need to implement getLikes function as you wish or can do the operation inside foreach loop.
There a note that you need to pay attention: you need to query for each product to get likes. It is better to join tables and format your array as your need in a loop.
Maybe you can create a new array and use the foreach construct to add the previous values and the new values.
$new_array = array();
foreach($result_json as $result){
$new_array[] = array(
'id' => $result['id'],
'likes' => getlikes($result['id'])
);
}
function getlikes($id){
// your code to get likes number with mysqli_num_rows()
}
echo json_encode($new_array);
You should join the 'postsLikes' table in your original query to pull in all the data you need with a single trip to the database.
Something like this:
(Guessing on how your tables are setup)
$query = "
SELECT
P.* ,
L.Likes
FROM postsTable P
LEFT JOIN postsLikes L ON L.Post_id = P.Post_Id
WHERE
P.Post_AgeFrom < :age AND
:age < P.Post_AgeTo AND
P.Post_Reviewed = 1 ";
$params = array( "age" => $age );
$pdo = new PDO('mysql:dbname=testdb;host=127.0.0.1', $user, password);
$stmt = $pdo->prepare( $query );
$stmt->execute( $params );
$results = $stmt->fetchAll( PDO::FETCH_ASSOC );
$response = array( "results" => $results );
echo json_encode( $response );
Other bits of advice:
1) Use bound parameters to prevent SQL injection.
2) Don't manually create any of the JSON in your response, create the response array first and let json_encode do the rest of the work

Add element and key to array php

I'm trying to add an element to array, but I get a weird output. The code is the following:
$getalltokens = $db->query("SELECT * FROM Tables WHERE available = '$comp'");
while ($row = $getalltokens->fetch(PDO::FETCH_ASSOC))
{
$fid = $row['FID'];
$tok = $row['token'];
$sql = $db->query("SELECT Firstname,Lastname FROM Users WHERE Token = '$tok'");
$rez = $sql->fetch(PDO::FETCH_ASSOC);
$names[] = $rez;
$fidzy = array(
'FID' => $fid
);
array_push($names, $fidzy);
}
$getalltokens = $db->query("SELECT FID FROM Tables WHERE available = '$comp'");
$tokenz = $getalltokens->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($names);
And the output I get is:
[{"Firstname":"Test","Lastname":"Test"},{"FID":"5"},
{"Firstname":"Test2","Lastname":"Test2"},{"FID":"4"}]
While what I need is the FID to be inside the $names array, so it would be more like:
[{"Firstname":"Test","Lastname":"Test","FID":"5"}]
$rez['FID'] = $fid; /* Added */
$names[] = $rez;
/* $fidzy and array_push removed */
You can use instead of array_push() like
$arrayname[indexname] = $value;
if you use array_push()
<?php
$array[] = $var;
?>
Note: If you use `array_push()` to add one element to the array it's
better to use$array[] = because in that way there is no overhead of
calling a function.
Note: `array_push()` will raise a warning if the first argument is not an array. This differs from the `$var[]` behavior where a new array
is created.
Reference Array push
The solution to the specific problem at hand is selecting all the necessary data in a single query, removing the need to add elements to any array. This is done in the following fashion:
$sql = $db->query("SELECT
Users.Firstname,Users.Lastname,Tables.FID
FROM Users,Tables
WHERE Users.Token = Tables.token");
$rez = $sql->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rez);

Saving PDO-data in array

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 );

php query function / class

It must be Monday, the heat or me being stupid (prob the latter), but for the life of me I cannot get a simple php function to work.
I have a simple query
$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
Which I want to run through a function: say:
function functionname($input){
global $field1;
global $field2;
$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
while($row = mysql_fetch_array($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
mysql_free_result($sql);
}
So that I can call the function in numerious places with differeing "inputs". Then loop through the results with a foreach loop.
Works fine the first time the function is called, but always gives errors there after.
As said "It must be Monday, the heat or me being stupid (prob the latter)".
Suggestions please as I really only want 1 function to call rather than rewrite the query each and every time.
This is the error message
Fatal error: [] operator not supported for strings in C:\xampp\htdocs\functions.php on line 270
function functionname($input){
$sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$input'");
$result = array('field1' => array()
'field2' => array()
);
while($row = mysql_fetch_array($sql)) :
$result['field1'][] = $row['field1'];
$result['field2'][] = $row['field2'];
endwhile;
mysql_free_result($sql);
return $result;
}
it seems that somewhere the $field1 or $field2 are converted to strings and you cant apply the [] to a string...
i'd say that you have to do:
$field1 = array();
$field2 = array();
before the WHILE loop
The problem is that you so called arrays are strings!
global $field1;
global $field2;
var_dump($feild1,$feild2); //Will tell you that there strings
Read the error properly !
[] operator not supported for strings
And the only place your using the [] is withing the $feild - X values
GLOBAL must work because the error is telling you a data-type, i.e string so they must have been imported into scope.
another thing, why you selecting all columns when your only using 2 of them, change your query to so:
$sql = mysql_query("SELECT feild1,feild2 FROM table WHERE field_name = '$input'");
another thing is that your using mysql_fetch_array witch returns an integer indexed array, where as you want mysql_fetch_assoc to get the keys.
while($row = mysql_fetch_assoc($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
What I would do
function SomeFunction($variable,&$array_a,&$array_b)
{
$sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$variable'");
while($row = mysql_fetch_assoc($sql))
{
$array_a[] = $row['field1'];
$array_b[] = $row['field2'];
}
mysql_free_result($sql);
}
Then use like so.
$a = array();
$b = array();
SomeFunction('Hello World',&$a,&$b);
In my opinion, it's pretty unusual and even useless approach at all.
This function is too localized.
To make a general purpose function would be a way better.
<?
function dbgetarr(){
$a = array();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
$res = mysql_query($query);
if (!$res) {
trigger_error("dbgetarr: ".mysql_error()." in ".$query);
return FALSE;
} else {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
and then call it like this
$data = dbgetarr("SELECT field1,field2 FROM table WHERE field_name = %s",$input);
foreach ($data as $row) {
echo $row['field1']." ".$row['field1']."<br>\n";
}
To understand your issue, we need the error, however, are you sure you are going about this in the right way?
Why do you need to call the function multiple times if you are just changing the value of the input field?
You could improve your SQL statement to return the complete result set that you need the first time.. i.e. SELECT * FROM table GROUP BY field_name;
Not sure if that approach works in your scenario, but in general you should aim to reduce the number of round trips to your database.
I don't know, i right or not. But i advise to try this:
function functionname($input){
global $field1;
global $field2;
$sql = mysql_query("SELECT * FROM `table` WHERE `field_name` = '" . $input . "'");
while($row = mysql_fetch_assoc($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
mysql_free_result($sql);
}

Categories