JSON output for SELECT with Prepared Statement - php

I am trying to encode the results from SELECT query with prepared statement into JSON output. I have the following code but I can't get it working. Any help would be greatly appreciated.
$query = "SELECT Item.ItemID, Item.ItemName FROM Items"
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->store_result();
$numrows = $stmt->num_rows;
$stmt->bind_result($ItemID, $ItemName);
for ($i=0; $i <$numrows; $i++) {
$stmt->fetch();
$JSONArray = ["ItemID" => $ItemID,
"ItemName" => $ItemName
]
echo json_encode($JSONArray);
}

You should always add the items to the container array, not overwrite the whole array and encode & echo only once:
...
$JSONArray = []; // initialize to empty array
for ($i=0; $i <$numrows; $i++) {
$row = $stmt->fetch();
$ItemID = $row['ItemID'];
$ItemName = $row['ItemName'];
// add the new item in each iteration
$JSONArray[] = ["ItemID" => $ItemID,
"ItemName" => $ItemName
];
}
echo json_encode($JSONArray);

Don't you think it should be Items not Item ? also there's missing quote and semicolon.
$query = "SELECT Items.ItemID, Items.ItemName FROM Items";
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
echo json_encode($result);
Also for convention I'd suggest you to keep lowercase table names. :)

When creating the PDO Object add:
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
e.g.:
$db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
that helped in my case : )
as seen on https://stackoverflow.com/a/7030557/5764766

Related

Construct http_build_query with PDO and Select

I am trying to create an http_build_query array but it is inserting some diferent characters, this is my Code:
function Conectar(){
try{
$opcoes = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8');
$con = new PDO("mysql:host=localhost; dbname=*****;", "*****", "*****", $opcoes);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $con;
} catch (Exception $e){
echo 'Erro: '.$e->getMessage();
return null;
}
}
$pdo = Conectar();
$sql = "
SELECT dominio
FROM dominios_extraidos
WHERE verificado='0' LIMIT 3
";
$stm = $pdo->prepare($sql);
$stm->execute();
while ($rows = $stm->fetch()) {
$query = http_build_query(array(
'domains' => array(
''.$rows['dominio'].'',
)
));
print_r($query);
}
Creating this output:
domains%5B0%5D=0002021web.com.br%0Adomains%5B0%5D=007import.com.br%0Adomains%5B0%5D=00pet.com.br%0A
But this is my desire output:
domains%5B0%5D=0002021web.com.br&domains%5B1%5D=007import.com.br&domains%5B2%5D=00pet.com.br
My desire output could be generated manually using this code:
$query = http_build_query(array(
'domains' => array(
'0002021web.com.br',
'007import.com.br',
'00pet.com.br',
)
));
print_r($query);
Thank you for your time :)
You want to build up your array properly first, so that it looks like your manual array, then use http_build_query:
$domains = ['domains' => []];
while ($rows = $stm->fetch()) {
$domains['domains'][] = trim($rows['dominio']);
}
$query = http_build_query($domains);
print_r($query);
Create an array of domains in the loop and then after the loop is complete pass it as a param to the http_build_query().
while ($rows = $stm->fetch()) {
$doms[] = trim($rows['dominio']);
}
$query = http_build_query( ['domains' => $doms] );
print_r($query);
This will produce
domains%5B0%5D=0002021web.com.br%0A&domains%5B1%5D=007import.com.br%0A&domains%5B2%5D=00pet.com.br%0A
which equates to
domains[0]=0002021web.com.br
&domains[1]=007import.com.br
&domains[2]=00pet.com.br
0A decoded is \n or Line Feed;
perhaps try sanitizing first with
$query= trim($query, "\x00..\x20\x7F");
this code remove ASCII character from 00 to 20 hex and 7f hex

pass parameters to sqli and bind results to json array

I am trying to pass parameter from $.ajax post to php page and then pass to database and get result to json.
after searching post .. I have prepared statements
$src1= $_POST['source1']; .. getting variable in src1
$stmt = $mysqli->prepare("SELECT * FROM tbl_beacons WHERE imei = ?");
$stmt->bind_param( "s", $src1);
$stmt->execute();
$stmt->bind_result($col1);
$emparray = array();
while($row =mysqli_fetch_assoc($stmt))
{
$emparray[] = $row;
}
echo json_encode($emparray);
$conn->close();
I am not getting results . i think i am not able to bind the variable to the statement correctly .
I also tried and prepare another
<?php
include("connect.php");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$src1='270113184309336860';
$rows = array();
$emparray = array();
if ($stmt = $mysqli->prepare("SELECT * FROM tbl_beacons WHERE imei = ?")) {
$stmt -> bind_param("s", $src1);
$stmt -> execute();
$rows = fetch($stmt);
}
while($row =mysqli_fetch_assoc($rows))
{
$emparray[] = $row;
}
echo json_encode($emparray);
$conn->close();
Please suggest where I am missing ?
update
while($row =mysqli_fetch_assoc($stmt))
with
while($row = $stmt->fetch())
update
$emparray[] = $row;
to
$emparray[] = $col1;
You may want to populate your json_encode array using
key value pairs; where the key corresponds to the data
structure you are using in your code, and the value
corresponds to its name in the database. Notice that these
two names do not have to be the same.
echo json_encode(array(
's' => $row->s,
'im' => $row->imei,
'name' => $row->NAME));

PDO fetchAll and foreach not returning first row

I have this in my PHP:
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$selected_client = $_POST['client'];
$sql = 'SELECT `cohort_id`,`cohort_name`, `cohort_description` FROM table_cohorts where client_id = :client';
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY) );
$stmt->execute(array(':client' => $selected_client));
foreach ($stmt as $row){
$result = $stmt->fetchAll();
}
header('Content-type: application/json');
echo json_encode($result);
This returns something that's ALMOST correct. It returns all the relevant, expected rows from my db table except for the first one. I'm guessing that I'm overwriting that somehow, but not sure where it's going wrong.
Unsure of why you've got a foreach loop in there. You'd use a foreach on $result to loop through the rows when what you want here is all the rows so you'd drop the loop.
foreach ($stmt as $row){
$result = $stmt->fetchAll();
}
and keep just this part.
$result = $stmt->fetchAll();
Just use
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
and get rid of the foreach loop.

returning multiple rows from mysql in php

I'm trying to write a PHP-script that will fetch multiple rows from MySQL and return them as a JSONObject, the code works if I try to only fetch 1 row but if I try to get more than one at a time the return string is empty.
$i = mysql_query("select * from database where id = '$v1'", $con);
$temp = 2;
while($row = mysql_fetch_assoc($i)) {
$r[$temp] = $row;
//$temp = $temp +1;
}
If I write the code like this it returns what I expect it to, but if I remove the // from the second row in the while loop it will return nothing. Can anyone explain why this is and what I should do to solve it?
You are using an obsolete mysql_* library.
You are SQL injection prone.
Your code is silly and makes no sense.
If you really wan to stick to it, why simply not do:
while($row = mysql_fetch_assoc($i)) {
$r[] = $row;
}
echo json_encode($r);
And finally, an example using PDO:
$database = 'your_database';
$user = 'your_db_user';
$pass = 'your_db_pass';
$pdo = new \PDO('mysql:host=localhost;dbname='. $database, $user, $pass);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try
{
$stmt = $pdo->prepare("SELECT * FROM your_table WHERE id = :id");
$stmt->bindValue(':id', $id);
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
catch(\PDOException $e)
{
$results = ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine());
}
echo json_encode($results);
You don't need the $temp variable. You can add an element to an array with:
$r[] = $row;

Php pdo foreach

Here I have php pdo function to get json from database
try {
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->prepare("SELECT id_tabele,naziv FROM track_aktivnosti WHERE prvi=:prvi AND id_akt=:id_akt AND tabela=:tabela");
$result->execute(array(':prvi' => $_POST['prvi'], ':id_akt' => $_POST['id_akt'], ':tabela' => $_POST['tabela']));
$result = $result->fetchAll();
foreach($result as $r) {
$temp = array();
$temp[] = array('id' => (int) $r['id_tabele'], 'ime_prezime' => (string) $r['naziv']);
}
$table = $temp;
$jsonTable = json_encode($table);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo $jsonTable;
but I get just one result, one element in json etc.
[{"id":1,"ime_prezime":"Pera Peric"}]
other element I can't get. WHY?
I must get json like this:
[{"id":1,"ime_prezime":"Pera Peric"},[{"id":2,"ime_prezime":"Laza Lazic"}] ]
but I get only 1.st element and other not ...
You are overwriting the array inside the foreach on each iteration. This essentially means that the array is emptied on each iteration. The array will only contain the values from the last iteration. Move the $temp = array(); declaration outside the loop to fix this:
$temp = array(); // intialize the array
foreach($result as $r) {
$temp[] = array(
'id' => (int) $r['id_tabele'],
'ime_prezime' => (string) $r['naziv']
);
}
The above fix will make your code work, but I recommend using the approach using SQL aliases as shown in #YourCommonSense's answer below.
You are doing a whole lot of useless operations. It's no wonder why you got lost.
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$sql = "SELECT id_tabele id, naziv ime_prezime FROM track_aktivnosti
WHERE prvi=? AND id_akt=? AND tabela=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($_POST['prvi'], $_POST['id_akt'], $_POST['tabela']));
echo json_encode($result->fetchAll());
declare
$temp = array();
out side the loop since you have this inside the loop and on each iteration its declared as new array and previous entries are wiped.
i.e.
$temp = array();
foreach($result as $r) {
$temp[] = array('id' => (int) $r['id_tabele'], 'ime_prezime' => (string) $r['naziv']);
}

Categories