user5075858 user5075858 - 2 years ago 110
SQL Question

PHP7/mysql PDO custom function

I'm trying to migrate an application written in PHP 5.2, but I'm having trouble creating the correct syntax for custom functions. This works perfectly in the old syntax, but I get a fatal error with this.

Essentially, I'd like to create a function to make it easy to get an email address from a database table that's associated with a unique id. I wrote the code below based on what works in PHP 5.2.

function getemail($id) {
$email_query = $con->query("SELECT email FROM admin WHERE id='$id'");
$rs = $email_query->fetch(PDO::FETCH_ASSOC);

return $rs;

Then I could use something like below to call this function.

foreach($con->query('SELECT * FROM admin') as $row) {
echo $row['id'] . ' ' . $row['name'] . ' ' . getemail($row['id']) . '<br>';

Any direction to help with this issue is greatly appreciated.

Answer Source

Ok, I have a tool for such a transition, which combines the simplicity of old mysql functions with safety of PDO (if used properly) - Simple yet efficient PDO wrapper

Having set it up, all you need is a code like this:

function getemail($id) {
    return DB::run("SELECT email FROM admin WHERE id=?", [$id])->fetchColumn(); 

called like this

echo getemail(1); //
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download