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
Related
I have some sql statements that accepts a number and if that number is equal to the value of a column in a database, it should return all rows in the database that has the same value. Unfortunately the rows only return blog_post_id that has a value 0.
This is my codes below:
<?php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$blog_post_id = !empty($_POST['blog_post_id']) ? $_POST['blog_post_id']
: '';
$pdo=new PDO("mysql:dbname=db;host=localhost","username","password",
$options);
$statement=$pdo->prepare("SELECT * FROM comment WHERE blog_post_id =
'$blog_post_id'");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
if ($json)
echo $json;
else
echo json_last_error_msg();
?>
You are actually missing the point of using the function prepare() and you need to check if the query does actually return any results..
<?php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
);
$blog_post_id = !empty($_POST['blog_post_id']) ? $_POST['blog_post_id'] : '';
$pdo = new PDO("mysql:dbname=db;host=localhost", "username", "password", $options);
$statement = $pdo->prepare("SELECT * FROM comment WHERE blog_post_id = ?");
$statement->execute([$blog_post_id]);
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = array();
if (count($results) > 0) {
foreach ($results as $row) {
$json[] = array(
'id' => $row['blog_post_id'],
'Field' => $row['Column'],
'AnotherField' => $row['AnotherColumn'],
'AnotherField1' => $row['AnotherColumn1'],
'ETC' => $row['AnotherColumnName']
);
}
echo json_encode($json);
} else {
echo "no data found";
}
?>
You should do variable binding like so:
$pdo=new PDO("mysql:dbname=db;host=localhost","username","password", $options);
$statement=$pdo->prepare("SELECT * FROM comment WHERE blog_post_id = :blog_post_id");
$statement->execute(['blog_post_id' => $blog_post_id]);
This will also prevent 1st level SQL-Injection as described here: Are PDO prepared statements sufficient to prevent SQL injection?
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
I have a table in my server database with the following columns:
|---category--|---name---|---description---|
So, lets say for example that we have the following data inside the table:
|---CategoryA--|---name1---|---description1---|
|---categoryB--|---name2---|---description2---|
|---categoryA--|---name3---|---description3---|
|---categoryA--|---name4---|---description4---|
I would like to create a .php file, and when i call it from my Android app i would like to get a JSON as response. The json file would like to have the following format:
{
"CategoryA":[
{"name":"name1","description":"description1"},
{"name":"name3","description":"description3"},
{"name":"name4","description":"description4"}
],
"KatigotiaB":[
{"name":"name2","description":"description2"}
]
}
I have created a .php file that returns me the data in JSON format, but not in the specific format i want. Here is my .php file:
<?php
header('content-type: text/html; charset=utf-8');
try {
$pdo = new PDO('mysql:host=****;dbname=****', '****', '****', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$stmt = $pdo->prepare("SELECT * FROM `db`.`table`;");
$stmt->execute();
$results = array();
while ($obj = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($results, $obj);
}
function replace_unicode_escape_sequence($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UTF-16BE');
}
$str = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', json_encode($results));
echo $str;
?>
and the result is:
[{"category":"CategoryA","name":"name1","description":"description1"},
{"category":"CategoryB","name":"name2","description":"description2"},
{"category":"CategoryA","name":"name3","description":"description3"},
{"category":"CategoryA","name":"name4","description":"description4"}]
As i'm an Android developer and my php knowledge is limited, how could i recreate my .php file in order to get the correct JSON format?
UPDATE:
that works
foreach ($nameDescriptionPairs as $nameDescriptionPair) {
$result[$row['category']][] = array(
'name' => $nameDescriptionPair['name'],
'description' => $nameDescriptionPair['description']
);
}
Solution #1 (simple):
<?php
$host = 'localhost';
$database = '******';
$user = '******';
$password = '******';
$result = [];
try {
$pdo = new PDO(
"mysql:host=$host; dbname=$database;",
$user,
$password,
[PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"]
);
$stmt = $pdo->prepare("SELECT category, name, description FROM `YOUR_TABLE_HERE`");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$row['category']][] = [
'name' => $row['name'],
'description' => $row['description'],
];
}
} catch (Exception $e) {
echo 'ERROR: ' . $e->getMessage();
}
header('content-type: application/json; charset=utf-8');
echo json_encode($result);
Solution #2 (geeky):
One note to my code: I used hex conversion to prevent problems with quotes. Thus, even if any column has any number of ", the code will work fine.
<?php
function hexToStr($hex) {
$string = '';
for ($charIter = 0; $charIter < strlen($hex) - 1; $charIter += 2) {
$string .= chr(hexdec($hex[$charIter] . $hex[$charIter + 1]));
}
return $string;
}
//----------------------
$host = 'localhost';
$database = '******';
$user = '******';
$password = '******';
$result = [];
try {
$pdo = new PDO(
"mysql:host=$host; dbname=$database;",
$user,
$password,
[PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"]
);
$query = <<<QUERY
SELECT category, CONCAT('[', GROUP_CONCAT( CONCAT( '{"name":"', hex( name ) , '", "description":"', hex( description ) , '"}' ) ), ']') raw_json
FROM `YOUR_TABLE_HERE`
GROUP BY category
QUERY;
$stmt = $pdo->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$nameDescriptionPairs = json_decode($row['raw_json'], true);
foreach ($nameDescriptionPairs as $nameDescriptionPair) {
$result[$row['category']][] = [
'name' => hexToStr($nameDescriptionPair['name']),
'description' => hexToStr($nameDescriptionPair['description'])
];
}
}
} catch (Exception $e) {
echo 'ERROR: ' . $e->getMessage();
}
header('content-type: application/json; charset=utf-8');
echo json_encode($result);
One major issue is you're setting the content-type to text/html. You're not printing HTML, this should be set to JSON:
header('content-type: application/json; charset=utf-8');
Not sure if it has any effect, but your callback is unnecessary:
$str = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', json_encode($results));
If you truly don't want json_encode to escape unicode, use the JSON_UNESCAPED_UNICODE option found here: http://php.net/manual/en/function.json-encode.php
$str = json_encode($results, JSON_UNESCAPED_UNICODE);
Beyond that, you could also use JSON_PRETTY_PRINT to format it, but line breaks and such shouldn't matter to the app interpreting the JSON if it is made aware that it is JSON (what setting content-type correctly should do).
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;
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']);
}