I want help converting this code which is using php PDO function but i want to use mysqli, please help me do this.
<?php
// PDO connect *********
function connect()
{
return new PDO('mysql:host=localhost;dbname=smartstorey', 'root', 'Sph!nx2g0!!', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
$pdo = connect();
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM product WHERE auto_complete_product_name LIKE (:keyword)";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
// put in bold the written text
$country_name = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['auto_complete_product_name']);
// add new option
echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['auto_complete_product_name']).'\')">'.$country_name.'</li>';
}
?>
Down under are the two methods from which you can choose. Notice that I didn't use any OOP or functions for the code structure (but MySQLi methods are OOP), because I wanted to provide a compact view of all steps.
How to use MySQLi prepared statements and exception handling
OPTION 1: Use get_result() + fetch_object() or fetch_array() or fetch_all():
This method (recommended) works only if the driver mysqlnd (MySQL Native Driver) is installed/activated. I think the driver is by default activated in PHP >= 5.3. Implement the code and let it run. It should work. If it works, then it's perfect. If not, try to activate mysqlnd driver, e.g. uncomment
extension=php_mysqli_mysqlnd.dll
in php.ini. Otherwise you must use the second method (2).NB: How to use fetch_array() instead of fetch_object():
Make the corresponding changes in the "Display data" code too:
NB: How to use fetch_all() instead of fetch_object():
Make the corresponding changes in the "Display data" code too:
OPTION 2: Use store_result() + bind_result() + fetch():
Works without the driver mysqlnd (MySQL Native Driver).
In the end I'd suggest you to use an object-oriented approach, like implementing a MySQLiConnection class (for handling the db connection) and a MySQLiAdapter class (for handling the query functionality). Both classes should be instantiated only once. The MySQLiConnection should be passed as constructor argument to the MySQLiAdapter class. MySQLiAdapter class needs an MySQLiConnection class for querying the db and for receiving the results. You could extend their use by implementing corresponding interfaces too, but I tried to keep my explanation simple.
I'd also suggest you to use PDO instead of MySQLi. One of the reasons I've discovered when I implemented this code: the somewhat challenging exception handling system in MySQLi.
Good luck!