I have some php that is receiving a variable from jquery and querying the DB. I recently learned that I need to use PDO to prevent SQL Injections and such so I have been trying to convert my query to it. I am new at php anyway so this is turning out to be more difficult than I thought (even though all the articles I read looked quite straightforward)...The DB connection is working and 'name' is receiving the right value but it is not updating the page like it used to. I am guessing it has to do with my loop that contains the json_encode. Below is my old php and then my attempt at turning it into PDO format.
Old PHP:
$dbstylename = $_POST['name'];
$result = mysql_query("SELECT * FROM style where stylename like '$dbstylename'");
$array = mysql_fetch_row($result);
echo json_encode($array);
mysql_close($con);
?>
New PDO attempt:
<?php
include 'db.php';
try {
$dbConnection = new PDO('mysql:host=$dbhost;dbname=$dbhost;', $user, $pass);
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
#Prepare the query
$dbstylename = $_POST['name'];
$result = $dbConnection->prepare('SELECT * FROM style where stylename like :dbstylename');
#bind
$result->bindParam(':dbstylename', $dbstylename, PDO::PARAM_STR);
#execute
if ($result->execute(array($dbstylename))) {
while ($row = $result->fetch()) {
json_encode($row);
}
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
================UPDATE==============================
In addition to @MadaraUchiha great answer and follow up help I had to change my jQuery from this (which worked before PDO):
$.ajax({
url: '../test.php',
type: 'POST',
data: {'name' : target},
dataType: 'json',
success: function(data) {
var styleid = data[0];
var stylename = data[1];
var stylecss = data[2];
$('#codeTest').html("<b>id: </b><br />"+styleid+"<br /><b> stylename: </b><br />"+stylename+"<br /><b> stylecss: </b><br />"+stylecss);
}
});
To this:
$.ajax({
url: '../test.php',
type: 'POST',
data: {'name' : target},
dataType: 'json',
success: function(data) {
var styleid = data.styleid;
var stylename = data.stylename;
var stylecss = data.stylecss;
$('#codeTest').html("<b>id: </b><br />"+styleid+"<br /><b> stylename: </b><br />"+stylename+"<br /><b> stylecss: </b><br />"+stylecss);
}
});
echoing the encoded result. (Though if you want to only echo one row, you don't need thewhileloop.)