Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Let me start with this, it's great that you're working on improving from the old ext/mysql to PDO. Well done!</p> <p>Well, first, you don't need to check for errors! Since you've set <code>PDO::ATTR_ERRMODE</code> to <code>PDO::ERRMODE_EXCEPTION</code>, an Exception would be thrown if there's an error! so your if statement on</p> <pre><code>if ($result-&gt;execute(array($dbstylename))) { </code></pre> <p>Is redundant.</p> <p>Second, since you've already bound the parameter with <code>bindParam</code>, passing it again with the array is also redundant.</p> <p>Lastly, if you only expect one result, you can drop the <code>while</code> loop, or even use <code>$result-&gt;fetchAll(PDO::FETCH_ASSOC)</code> to fetch all of the result into a single array.</p> <hr> <p>Now for the real problem, you aren't echoing the result of <code>json_encode()</code>, like you used to in the first script (You're just calling it without doing anything with the result).</p> <p>Corrected code, with all of the above taken into account:</p> <pre><code>&lt;?php include 'db.php'; try { $dbConnection = new PDO('mysql:host=$dbhost;dbname=$dbhost;', $user, $pass); $dbConnection-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); #Prepare the query $dbstylename = $_POST['name']; $result = $dbConnection-&gt;prepare('SELECT * FROM style where stylename like :dbstylename'); #bind $result-&gt;bindParam(':dbstylename', $dbstylename, PDO::PARAM_STR); #execute $result-&gt;execute(); $row = $result-&gt;fetch(PDO::FETCH_ASSOC); echo json_encode($row); } catch(PDOException $e) { echo 'ERROR: ' . $e-&gt;getMessage(); } ?&gt; </code></pre> <p>Other than that, you're PDO code is flawless, keep it up!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload