colshrapnel / safemysql

A real safe and convenient way to handle MySQL queries.
Apache License 2.0
395 stars 197 forks source link

How to make sure the query executed successfully? #24

Closed faizanqadri closed 10 years ago

faizanqadri commented 10 years ago

Lets suppose I query a database and it failed with error of duplicate entry or the lie so how can I detect that so I can throw eception accordingly. That way I can easily take care of multiple query insertion to rollback if one executes and other one failed. Also on select how can I display the returned result set by do while or the like?

colshrapnel commented 10 years ago

you can set errmode to exception and enclose your query call in try-catch to catch this error

$db = new SafeMySQL('errmode' => 'exception');
try {
    $db->query($sql,$pid,$data,$data);
} catch Exception($e){
    // if got here - then there was error
}
// updated succesfully```

Is it what you were asking for?

faizanqadri commented 10 years ago

Yes I am asking for it & I also requested on select query how can I display the returned result set by do while or the like?

Its quite simple I guess it'll call the exception is any of the query filed

colshrapnel commented 10 years ago

Oh, yeah, sorry. In general, you don't have to use while(), but foreach() instead, like this

// First, get all the data returned in array
$data = $db->getAll("SELECT * FROM table");
// then iterate it over 
foreach ($data as $row){   
    echo $row['name'];
}

it's going to be especially handy when you are using templates, and your loop is situated somewhere distant from the place where you're getting your data

Anyway, you can use old while method as usual:

$result = $db->query("SELECT * FROM table");
while ($row = $db->fetch($result)){   
    echo $row['name'];
}
faizanqadri commented 10 years ago

Thanks alot for your quick response. I have recommended my new recruits to use your awesome class.

colshrapnel commented 10 years ago

Thank you for your feedback! Feel free to ask any further questions!