MySQL & PDO : about efficiency - mysql

I have the following code :
<?php
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=*****;dbname=****", "****", "*****");
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
# statement handle (prevents injection)
$STH = $DBH->prepare("SELECT Adresse FROM Agences");
$STH->execute();
# statement handle (prevents injection)
$STHNAMES = $DBH->prepare("SELECT `numero-agence` FROM Agences");
$STHNAMES->execute();
$storeArray = Array();
$nameArray = Array();
while ($row = $STH->fetch()) {
$storeArray[] = $row['Adresse'];
}
while ($row = $STHNAMES->fetch()) {
$nameArray[] = $row['numero-agence'];
}
echo json_encode(
Array("theAddress" => $storeArray,
"theName" => $nameArray)
);
}
catch(PDOException $e) {
echo 'There was an issue inserting thing into database: '.$e->getMessage();
}
?>
My question is : is there a way to combine the two queries and still have an associative array to send back to the client JSON-encoded ? (I am querying this bit of PHP with an ajax call, and need the resulting data)
Thanks.

Can be done in the same query:
# statement handle (prevents injection)
$STH = $DBH->prepare("SELECT Adresse, `numero-agence` FROM Agences");
$STH->execute();
$storeArray = Array();
$nameArray = Array();
while ($row = $STH->fetch()) {
$storeArray[] = $row['Adresse'];
$nameArray[] = $row['numero-agence'];
}

Related

getting error back from Prepared statement in case sql injection

I'm trying to test my prepared statement that is protecting one field to get the error message in case of SQL injection. I tried until now thousands of attacks, and all of the values I gave were accepted. Am I using a wrong syntax or attack? I can't see where the problem is. Here is my code:
try {
// $host = "localhost";
// $username = "root";
// $password = "root";
// $db_name = "pokemon";
$conn = new PDO('mysql:host='.$host.';dbname='.$db_name.';', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$meldung="";
$name =$_REQUEST['name'];
$gewicht = $_REQUEST['Gewicht'];
$größe =$_REQUEST['Größe'];
$spezies = $_REQUEST['Spezies'];
$stufe =$_REQUEST['Stufe'];
$atacke =$_REQUEST['Attacke'];
$array = explode(',', $_REQUEST['Attacke']);
$stmt = $conn->prepare("INSERT INTO Pokemon (`Name`,`Gewicht`,`grosse`,`spezies`,`stufe`) VALUES (:Name, '".$gewicht."', '".$größe."', '".$spezies."', '".$stufe."')");
$stmt->bindParam(':Name', $name);
// $stmt->bindParam(':Gewicht', $gewicht);
// $stmt->bindParam(':grosse', $größe);
// $stmt->bindParam(':spezies', $spezies);
// $stmt->bindParam(':stufe', $stufe);
$stmt->execute();
}
catch(PDOException $e)
{
$meldung = "Error: " . $e->getMessage();
echo $meldung;
}
thanks

multiple array for json from one table

I've an review table in my database and same has been associated with the products on my website, however while posting the json encode i am unable to see multiple array through my code.
Please help me in updating the same.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$id = $_GET['id'];
require('adminpanel/includes/application_top.php');
$sql = "SELECT * FROM drug_reviewpage WHERE fld_product_id='" . $id . "'";
$r = mysql_query($sql);
$res = mysql_fetch_array($r);
$result = array();
array_push($result, array(
"fld_review_message" => $res['fld_review_message'],
"fld_fullname" => $res['fld_fullname'],
"fld_rate" => $res['fld_rate'],
"fld_date" => $res['fld_date']
));
echo json_encode(array("result"=>$result));
mysql_close($conection);
}
?>

wordpress json_decode is not working, I am trying to get value form wp_option table

When I am trying to decode JSON with this code the output is
ArrayArray ( [0] => )
I do not know why WordPress doesn't support this
<?php
global $wpdb;
$mylink = $wpdb->get_results( "SELECT option_value FROM wp_options WHERE option_id=62167", ARRAY_N );
$raw = stripslashes_deep($mylink);
$data = array();
foreach ($raw as $json) {
echo $json;
$item = #json_decode($json, true);
$data[] = $item;
print_r($data);
}
?>
Hello you need to unserealize the data first when your query get data from database,
That is serealized data and when we get it from db we need to unserealize it.
global $wpdb;
$mylink = $wpdb->get_results("SELECT option_value FROM wp_options WHERE option_id=1223",ARRAY_A);
$raw = stripslashes_deep($mylink);
$data = $raw[0]['option_value'];
$datas = unserialize($data);
foreach ($datas as $key => $value) {
print_r($value);
}

How to add a row to array with PDO

How can I add a row to array using PDO. Previously i did it like this $message = array('status' => 'ok'; But when I try to use this in PDO like this it does't work
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$employees = $stmt->fetchAll(PDO::FETCH_OBJ);
$employees['status'] = 'ok';
$employees = array($employees);
$dbh = null;
header('Content-Type: application/json');
echo '{"key":'. json_encode($employees) .'}';
}
Try
$employees = $stmt->fetchAll(PDO::FETCH_ASSOC);
If you want to typecast $employees into an array, you should be using
$employees = (array)$employees;

mysql_num_rows() error

I am displaying an editable table in drupal with the following code
function _MYMODULE_sql_to_table($sql) {
$html = "";
// execute sql
$resource = db_query($sql);
// fetch database results in an array
$results = array();
while ($row = db_fetch_array($resource)) {
$results[] = $row;
$id = $row['id'];
$email = $row['email'];
$comment = $row['comment'];
// drupal_set_message('Email: '.$email. ' comment: '.$comment. ' id: '.$id);
}
// ensure results exist
if (!count($results)) {
$html .= "Sorry, no results could be found.";
return $html;
}
// create an array to contain all table rows
$rows = array();
// get a list of column headers
$columnNames = array_keys($results[0]);
// loop through results and create table rows
foreach ($results as $key => $data) {
// create row data
$row = array(
'edit' => l(t('Edit'),"admin/content/test/".$data['id']."/ContactUs", $options=array()),);
// loop through column names
foreach ($columnNames as $c) {
$row[] = array(
'data' => $data[$c],
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// add row to rows array
$rows[] = $row;
}
// loop through column names and create headers
$header = array();
foreach ($columnNames as $c) {
$header[] = array(
'data' => $c,
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// generate table html
$html .= theme('table', $header, $rows);
return $html;
}
// then you can call it in your code...
function _MYMODULE_some_page_callback() {
$html = "";
$sql = "select * from {contact3}";
$html .= _MYMODULE_sql_to_table($sql);
return $html;
}
However, I keep getting the mysql_num_rows() error as
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource. What is causing it?
Which version of Drupal are you using?
try db_affected_rows()
or db_num_rows()