Reputation: 3
I wrote this script where you go to localhost/censor.php/query and it sees if it is taken. Here is the code:
<?php
function curPageURL() {
$pageURL = 'http';
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80")
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
else
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
return $pageURL;
}
$test = curPageURL();
$test = str_replace('http://localhost/censor.php/',"",$test);
$con = mysqli_connect("localhost","root","creepers2","spider");
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
$usname = null;
$result = mysqli_query($con, "SELECT * FROM main WHERE urls='$test'");
while($row = mysqli_fetch_array($result) or die(mysqli_error($con))) {
$usname = $row['urls'];
if ($usname=$test)
echo "Taken!";
else
echo"YEAH!";
}
mysqli_close($con);
?>
If you to localhost/censor.php/queryinthedatabase it prints out taken. However, if you go to localhost/censor.php/querynotinthedatabase, it prints nothing. Help please?
Upvotes: 0
Views: 98
Reputation: 868
You are doing a simple query: SELECT * FROM main WHERE urls='$test'
. That's fine (SQL injections aside).
Now, you're fetching all results and looping through them by using while($row = mysqli_fetch_array($result) or die(mysqli_error($con)))
. That said, if there were no results, it won't loop through any objects as it can't fetch any.
You should use something like mysqli_num_rows
. For example:
$result = mysqli_query($con, "SELECT * FROM main WHERE urls='" . mysqli_real_escape_string($test) . "'");
if (mysqli_num_rows($result) == 1) {
echo "Taken!";
}
else {
echo "YEAH!";
}
Now you're doing the same query (selecting all rows where urls
is equal to $test
), but instead of looping through the returned rows, you count the amount of rows that the query returned. If it equals 1
, it's taken.
Also, please escape any user-input you put into your queries; don't get to be yet another victim of SQL injections. Never trust the user!
Upvotes: 2
Reputation: 23510
You are assigning a variable value inside an if statment which is wrong, you should use double equl coparison operator to compare them, simply change
if ($usname==$test)
Also to debug your query you should move your mysqli_error to the query itself
$result = mysqli_query($con, "SELECT * FROM main WHERE urls='$test'") or die(mysqli_error($con));
while($row = mysqli_fetch_array($result)) {
Your code is highly vulnerable to mysql injections, learn more in this usefull post How can I prevent SQL injection in PHP? you should use prepared statement to avoid any risk.
Upvotes: 0
Reputation: 4085
The problem is that you are using if ($usname=$test)
instead of if ($usname==$test)
Upvotes: 0