Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating a container function for a PDO query in PHP
    primarykey
    data
    text
    <p>Because I find PDO executions extremely hard to remember and find myself looking back at previous projects or other websites just to remember how to select rows from a database, I decided that I would try and create my own functions that contain the PDO executions and just plug in the data I need. It seemed a lot simpler than it actually is though...</p> <p>So far I have already created a connect function successfully, but now when it comes to create a select function I'm stumped for multiple reasons.<br> For starters there could be a variating amount of args that can be passed into the function and secondly I can't figure out what I should pass to the function and in which order.</p> <p>So far the function looks like this. <em>To keep me sane, I've added the "id" part to it so I can see what exactly I need to accomplish in the final outcome, and will be replaced by variables accordingly when I work out how to do it.</em></p> <pre><code>function sql_select($conn, **what to put here**) { try { $stmt = $conn-&gt;prepare('SELECT * FROM myTable WHERE id = :id'); $stmt-&gt;execute(array('id' =&gt; $id)); $result = $stmt-&gt;fetchAll(); if ( count($result) ) { foreach($result as $row) { print_r($row); } } else { return "No rows returned."; } } catch(PDOException $e) { echo 'ERROR: ' . $e-&gt;getMessage(); } } </code></pre> <p>So far what I've established that the function will need to do is</p> <ul> <li>Connect to the database (using another function to generate the $conn variable, already done)</li> <li>Select the table</li> <li>Specify the column</li> <li>Supply the input to match</li> <li>Allow for possible args such as <code>ORDER by 'id' DESC</code></li> </ul> <p>Lastly from this I would need to create a function to <b><i>insert, update</b></i> and <b><i>delete</i></b> rows from the database.</p> <p>Or, is there a better way to do this rather than functions?</p> <p>If anyone could help me accomplish my ambitions to simply simplify PDO executions it would be greatly appreciated. Thanks in advance!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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