I am now rewriting the old PHP5 scripts into PHP7, and I can’t figure out how to make the lookup of the words in the Database work. So I have two files db.php and dic_s.php
db.php
What I did here is just substituted mysql_ to mysqli_ and added a second paremeter $conn
<?php
class db {
function __construct()
{
global $dbh;
if (!is_null($dbh)) return;
$conn = mysqli_connect('localhost', 'user', 'password');
mysqli_select_db($conn, 'dbname');
mysqli_query($conn, 'SET NAMES utf8');
}
function select_list($query)
{
$q = mysqli_query($query);
if (!$q) return null;
$ret = array();
while ($row = mysqli_fetch_assoc($q)) {
array_push($ret, $row);
}
mysqli_free_result($q);
return $ret;
}
}
?>
dic_s.php
//getting date thru $_POST
if (isset($_POST['search'])) {
// connection to database
include('db.php');
$db = new db();
// filtering
$word = trim(mysqli_real_escape_string($_POST['search']));
// sql query
$sql = "SELECT * FROM dictionary WHERE `word` LIKE '$word' GROUP BY `id` ORDER BY `word`";
$row = $db->select_list($sql);
if(count($row)) {
$end_result = '';
foreach($row as $r) {
$end_result .= '<font color="lightblue" size="3" face="Arial">'.$r['word'] .
'</font><i>('.$r['forms'] .')</i>';
$end_result .= '<br>Also:<i><font color="white" size="2" face="Arial"> '.$r['alterword'].'</i></font>';
$end_result .= '<br><ol><font color="#89F0F5" face="Arial" size="4"> '.$r['meaning'] .' </font>';
} echo $end_result;
} else {
echo 'Nothing found.';
}
}
I get these results while trying to execute the code
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, object given in /dic_s.php on line 28
Warning: mysqli_query() expects at least 2 parameters, 1 given in /db.php on line 15
Nothing found.
For example, when I try to comply with errors and try to add the missing, it still won’t work
$q = mysqli_query($conn, $query);
Notice: Undefined variable: conn in /db.php on line 15
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /db.php on line 15