new mysqli(): how to intercept an ‘unable to connect’ error?

You need to tell mysqli to throw exceptions: mysqli_report(MYSQLI_REPORT_STRICT); try { $connection = new mysqli(‘localhost’, ‘my_user’, ‘my_password’, ‘my_db’) ; } catch (Exception $e ) { echo “Service unavailable”; echo “message: ” . $e->message; // not in live code obviously… exit; } Now you will catch the exception and you can take it from there.

Pass by reference problem with PHP 5.3.1 [duplicate]

I just experienced this same problem, calling bind_param via call_user_func_array and passing an array of parameters. The solution is to modify the values in the array to be referenced. It’s not elegant but it works. call_user_func_array(array($stmt, ‘bind_param’), makeValuesReferenced($passArray)); function makeValuesReferenced($arr){ $refs = array(); foreach($arr as $key => $value) $refs[$key] = &$arr[$key]; return $refs; }

How to insert into MySQL using mysqli

File sample.html <form action=”sample.php” method=”POST”> <input name=”name” type=”text”> <input name=”text” type=”text”> <input name=”submit” type=”submit” value=”Submit”> </form> File sample.php <?php if (isset($_POST[‘submit’])) { mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli(‘localhost’, ‘user’, ‘password’, ‘mysampledb’); // replace every piece of data in SQL with question mark $sql = “INSERT INTO SampleTable (name, text) VALUES (?,?)” // 2 question … Read more

check if the query returns zero rows [duplicate]

You can use the num_rows on the dataset to check the number of rows returned. Example: $results = $mysqli->query(“SELECT ANNOUNCE_NUMBER,ANNOUNCEMENTS,ANNOUNCE_TYPE,POST_DATE FROM home ORDER BY ANNOUNCE_NUMBER DESC”); if ($results->num_rows === 0) { echo ‘No results’; } else { while ($obj = $results->fetch_object()) { //output results from database } }

Check to see if an email is already in the database using prepared statements

Should be something like this: // enable error reporting for mysqli mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // create mysqli object $mysqli = new mysqli(/* fill in your connection info here */); $email = $_POST[’email’]; // might want to validate and sanitize this first before passing to database… // set query $query = “SELECT COUNT(*) FROM users WHERE … Read more

How to make mysqli connect function?

As some users have suggested (and is the best way), return the mysqli instance function getConnected($host,$user,$pass,$db) { $mysqli = new mysqli($host, $user, $pass, $db); if($mysqli->connect_error) die(‘Connect Error (‘ . mysqli_connect_errno() . ‘) ‘. mysqli_connect_error()); return $mysqli; } Example: $mysqli = getConnected(‘localhost’,’user’,’password’,’database’);