Okay I’m new to php and mysql I tried to build a web page hit counter but my page counter dosen’t update correctly and it gets the following warnings listed below.
Warning: mysqli_query() expects at least 2 parameters, 1 given in
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in
Here is the php code below.
<?php
$page = $_SERVER['SCRIPT_FILENAME'];
// Query member data from the database and ready it for display
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT id page FROM mysql_counter_logs WHERE page = '$page'");
if (mysqli_num_rows($dbc) == 0) {
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"INSERT INTO mysql_counter_logs (page) VALUES ('$page')");
mysqli_query($dbc);
} elseif (mysqli_num_rows($dbc) == 1) {
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"UPDATE mysql_counter_logs SET hits = hits + 1 WHERE page = '$page'");
mysqli_query($dbc);
}
//Retreives the current count
$count = mysqli_fetch_row(mysqli_query($mysqli,"SELECT hits FROM mysql_counter_logs"));
if (!$dbc) {
// There was an error...do something about it here...
print mysqli_error();
}
//Displays the count on your site
print "$count[0]";
?>
An extract of your code :
First of all, according to the manual of mysqli_query, when used as a function :
Which means you have to pass your
$mysqlivariable as first parameter, and your query as a second parameter.What I don’t get is why you are using
mysqli_querythis way on the third line I copy-pasted, while you are using it correctly in the other parts of your code ?Are you sure you mean to use that function, here ?
Also, knowing on which lines you are getting those error messages might help 😉
Check you don’t do anything else “wrong” there — like ” mysqli_query() expects at least 2 parameters, 1 given “
Thinking about it :
mysqli_querywill return booleanfalseif there is an error.In that case, you should not call
mysqli_num_rowson the return value ofmysqli_query, as it’s not a validmysqli_result— hence the second error message.You are checking for
$dbcat the end of your script, but it might be interesting to check it too a biit sooner — actually, after each call tomysql_query, I’d say.Also, as a sidenote : you probably don’t need to instance the mysqli class that many times : just instanciate it once, and then use the
$mysqlivariable for there rest of your script.Just for security, and to avoid any trouble, you might also want to use
mysqli_real_escape_stringon the$pagevariable, before injecting it into the queries.Oh, and, btw : you might be interested by the INSERT … ON DUPLICATE KEY UPDATE Syntax that MySQL allows to use 😉
(Well, that is if
pageis the primary key of your table, at least…)