tags:

views:

84

answers:

3

I'm new to php and mysql I think I misplaced the mysqli_real_escape_string() I keep getting the following warning on line 3.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in

Here is the php code.

<?php

$page = mysqli_real_escape_string($_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')");
} 

if ($dbc == 1) {
  $dbc = mysqli_query($mysqli,"UPDATE mysql_counter_logs SET hits = hits + 1 WHERE page = '$page'");
}

//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]";

?>

Also is there a way i can make this code more security proof from XSS attacks. Thanks

A: 

You are creating an instance already, you should be using $mysqli->real_escape_string OO-style, not procedural style.

meder
where do I place this at?
new
Actually - I wasn't paying attention. You need to feed the handle as the first parameter.
meder
+1  A: 

There are several things that are incorrect with your code sample.

Firstly mysqli_real_escape_string needs a connection to be established before you call it. Secondly, you need to pass that connection to mysqli_real_escape_string. Thirdly, you're mixing the object version of the mysqli api with the procedural version. You need to choose one and stick to it.

If you're going to use the object version, then you need to do something like the following:

$con = new mysqli(...);
$clean_data = $con->real_escape_string($your_string);
$con->query("SELECT ... FROM ... WHERE .. ='$clean_data'");

And so forth.

If you're going to go the procedural route then you need to do:

$con = mysqli_connect(...);
$clean_data = mysqli_real_escape_string($con, $your_string);
$result = mysqli_query($con, "SELECT ... FROM ... WHERE ... = '$clean_data');

http://php.net/mysqli

Stephen Caldwell
what is the difference between object and procedural?
new
It's not particularly easy to sum it up in a comment so I'll link you to a tutorial: http://devzone.zend.com/node/view/id/638
Stephen Caldwell
A: 

The first argument (if you are using the procedural version) is the link created with mysqli_connect(). There is an example of both the object oriented and procedural styles at http://www.php.net/manual/en/mysqli.real-escape-string.php.

mcrumley