Ok so the problem is... i m a newbie and i m trying to understand what is happening.Im sending through an html form this data(name,email) using POST in a database.I understand the logic behind it all but what basically happens is that everytime I enter a name,any name,it echoes the else statement:"there is already a user with that name". and it sends back the first name in the database.when there s nothing,it sends nothing. So here's the chunk:
$query= "SELECT* from users where username='".$_POST['name']."'";
$result = mysql_query($query);
if (!$result){
$query = "INSERT into users (username, email, password) values
('".$_POST["name"]."', '".$_POST["email"]."',
'".$passwords[0]."')";
$result = mysql_query($query);
if ($result){
echo "It's entered!";
} else {
echo "There's been a problem: ".mysql_error();
}
} else {
echo "There is already a user with that name: <br />";
$sqlAll = "select * from users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
You may want to check mysql_num_rows() rather than checking for !$result, I think that if the query is sucsesfull you'll get a resource back, even though it contains zero rows.
You may also want to read up on: http://php.net/manual/en/security.database.sql-injection.php
ESCAPEEEEE
Firstly, you need to learn about escaping.
Have you never heard of little Johnny DROP TABLES?
http://xkcd.com/327/
Serious business
The reason why it always returns, is because the response in $result is actually a resource data type. And that will always when cast as a boolean be true. (And since your query shouldn't fail).
You should fetch the result. For example. (This isn't the best way, but it is a way to do it).
mysql_fetch_row(result)
Per the manual, mysql_query will return false when there is an error - "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error."
see no violation in your code. first mysql_query executes with no error and always returns true. try to test returned rows count like this:
if (mysql_num_rows($result) == 0) {
//insert record
} else {
// show alreay exists
}
First of all, you are testing for:
if (!$result)
which will evaluate to true only if the query fails.
You should also sanitize all input before using it in SQL queries.
Related
I'm fairly new to php and have a question. I have an HTML form that has a SELECT auto-populated from an SQL table via PHP. The dropdown is populated with all users with the level of "Admin" or "Moderator". This is the code to connect:
$con = mysqli_connect("localhost", "root", "", "database") or die("Error " . mysqli_error($con));
And the dropdown itself:
<form name="htmlform" role="form" method="POST" action="result.php">
<select id="user" name="user" required>
<option selected disabled>User</option>
<?php
$result = $con->query("SELECT username FROM users WHERE level='admin' OR level='moderator' ORDER BY level");
while ($row = $result->fetch_assoc())
{
$username = $row['username'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
?>
</select>
This works perfectly. The problem I'm having is that I am trying to reuse the data from this form (specifically $_POST['user']) on another page to auto-populate another field in a form. I need to see if the 'user' is an Admin or not and return $other as either "y" (Admin) or "n" (not Admin), which will then be added to another table.
Here's my code on the 2nd page (result.php):
$user=$_POST['user'];
$query = $con->query("SELECT level FROM users WHERE username=$user");
$variable=mysqli_query($con, $query);
if ($variable=="admin") {
$other = 'y';
} else {
$other='n';
}
At the moment all output for $other is "n" regardless of anything. So, obviously I have an error in the code, but don't know enough php to be able to spot or correct it.
Please could someone help point out the error?
text values have to be wrapped in quotes in a query
$query = $con->query("SELECT level FROM users WHERE username='$user'");
You also look like you were trying to execute that same query twice here:
$query = $con->query("SELECT level FROM users WHERE username=$user");
$variable=mysqli_query($con, $query);
this is not legal usage.
Also when you run this line
$variable=mysqli_query($con, $query);
$variable is not a value, but a mysqli_result object that will contain a resultset or FALSE if the query failed, but definitely not the content if the id column in your query.
However if you are using data got from the user, it is not safe to assume thay are not attempting a SQL Injection Attack
So you should use Prepared and Parameterised queries like this
$stmt = $con->prepare("SELECT level FROM users WHERE username=?");
$stmt->bind_param('s', $_POST['user']);
$stmt->execute();
I think you shoud start by reading the PHP manual for the mysqli extension
(Without getting into issues about best practices ...)
Your second code snippet's usage of the return value from mysql_query() is problematic.
The PHP Manual states:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
Hence, $variable is a PHP resource and cannot ever be equal to a string.
Use tripple === equals when possible. You still need to "fetch" the record from the result resource (you managed to to do this in the first code snippet).
Generally speaking ...
$result = mysqli_query($con, $query);
$record = result->fetch_assoc();
//if(result->fetch_assoc()['level'] === 'admin') in PHP 5.4 and up.
//or
//if(mysqli_query($con, $query)->fetch_assoc()['level'] === 'admin') in PHP 5.4 and up.
if($record['level'] === 'admin')
{
}
else
{
}
Cheers!
According with mysqli_query doc:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
So don't expect to get database value directly from call, you are comparing a mysql_result object (you made a SELECT) versus a constant string. You need to get your data from mysql_result object and then you can make comparison.
This code should work for you:
$user = $_POST['user'];
$sql = "SELECT level FROM users WHERE username={$user}";
$variable = mysqli_query($con, $sql)->fetch_row();
if ($variable[0]=="admin") {
$other = 'y';
} else {
$other='n';
}
<?php
$uname=$_POST['uname'];
$pwd=$_POST['pwd'];
$result="";
echo($uname.'</br>');
echo($pwd);
$con=mysql_connect("localhost","root","");
mysql_select_db("user_login_test",$con);
$sql="SELECT * FROM userlogin WHERE username='".$uname."'";
if($result=mysql_query($sql))
{
echo($result);
echo("Extracted<br>");
}
else
{
echo("NOT Extracted");
}
while($row = mysql_fetch_array($result))
{
echo $row['username'] . " " . $row['password'];
echo "<br />";
}
?>
I am doing above code for extracting values. If Username matches it show the value but if I give wrong input text it also shows "Extracted" with no value why? Please help me???
As explained in the PHP manual entry for the mysql_query() function:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
Your $result variable therefore holds a MySQL resource irrespective of whether there is a match on the username column: testing such a resource using if will always evaluate to TRUE (unless the query itself threw an error).
The manual goes on to explain:
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.
In your case, you could test using mysql_num_rows() to determine whether any records were returned by the query (i.e. whether the WHERE condition was satisfied).
You have write wrong logic for extract username.
I have modify your code check it.
$sql="SELECT * FROM userlogin WHERE username='".$uname."'";
$result=mysql_query($sql)
if(mysql_num_rows($result)>0)
{
echo("Extracted<br>");
}
else
{
echo("NOT Extracted");
}
I have a strange mysql-thing going on here, it is about the following code:
$res = mysql_query("SELECT * FROM users WHERE group='".$group."'");
if (mysql_num_rows($res)==1) {
$row = mysql_fetch_assoc($res);
$uid = $row['uid'];
$user_update = mysql_query("UPDATE fe_users SET group = 5 WHERE group='".$group."'");
return 'ok';
} else {
return 'not ok';
}
I am checking, if there is a user with the group = $group. If so, the group is updated to 5 and after that the string "ok" is returned, if no user with group=$group exists, as you can see the string "not ok" is returned.
This should be very easy, but the problem now is, that if there is a user with group=$group, the update is done correctly, but instead of returning "ok", php returns "not ok", as if the change from the update is been taken into account for the above executed select retroactively. I dont understand this. Any help would be really appreciated.
Thanx in advance,
Jayden
I think 'group' is a reserved keyword that you have used as a field name, change it or use like
$res = mysql_query("SELECT * FROM users WHERE `group`='".$group."'");
and
$user_update = mysql_query("UPDATE fe_users SET `group` = 5 WHERE `group`='".$group."'");
and you can use count($res)==1 instead of mysql_num_rows($res)==1 if it is a problem.
Reference: Mysql Reserved keywords.
I am not sure if this has any merit but try using this style in your SELECT and UPDATE commands: WHERE group='$group', without using string joins. Other than that I can't seem to see why you are getting an update and not being returned "ok".
You are checking if mysql_num_rows($res)==1, so you'll return ok if there is exactly one user on that group. If there are two or more users, it will return not ok. Probably not what you want, right? I think you should check if mysql_num_rows($res)>=1.
You might consider modifying the placement of your brackets, and changing your num_rows check, like so:
$res = mysqli_query("SELECT uid FROM users WHERE `group` ='".$group."'");
if (mysqli_num_rows($res)>0) {//there was a result
while($row = mysqli_fetch_assoc($res)){
// grab the user id from the row
$uid = $row['uid'];
// and update their record
$user_update = mysqli_query("UPDATE fe_users SET `group` = 5 WHERE `group`='".$group."'");
if(mysqli_num_rows($user_update)==1){
return 'ok, updated user';
} else {
// database error
return 'not ok, unable to update user record';
}
}//end while row
}else{
return 'No results were found for this group.';
}
By selecting just the column you want, you reduce the query's overhead. By comparing the initial result to 0 instead of 1, you allow for groups with many members. By wrapping the update function in a while loop, you can loop through all the returned results, and update records for each one. By moving the test that returns 'ok'/'not ok' to check for success on the update operation, you're able to isolate database errors. The final else statement tells you if no update operation was performed because there are no members of the group.
BTW, for future-compatible code, I recommend using mysqli, as the "mysql_query" family of PHP functions are officially deprecated. See http://www.php.net/manual/en/mysqli.query.php for a quick start, it's largely the same thing.
A while ago I was poking around with SQLite, trying to port some of my sites to use it instead of MySQL. I got hung up on the lack of a function to count results, like PHP's mysql_num_rows(). After searching a little I discovered this mail list, which says (as I understand it) that SQLite doesn't have that functionality because it's inefficient. It states that it is bad form to write code that needs to know how many rows are returned.
I generally use mysql_num_rows to check for empty return results. For example:
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if (mysql_num_rows($results)) {
while ($row = mysql_fetch_array($results)) {
echo "<p>$row[whatever]</p>";
}
} else {
echo "<p>No results found</p>";
}
The vehement distaste for the concept of mysql_num_rows() in the SQLite community makes me wonder if it's that terribly efficient for regular MySQL in PHP.
Is there a better, more accepted way for checking the size of a MySQL result set in PHP besides mysql_num_rows()?
EDIT:
I'm not just using mysql_num_rows to get the count--I would use a COUNT query for that. I'm using it to check if there are any results before outputting everything. This is useful for something like displaying search results - it's not always guaranteed that there will be results. In SQLite world, I have to send one COUNT query, check if there is something, and then send a SELECT query to get everything.
You already have something that is telling you if you've got results in mysql_fetch_array(). It returns false if there are no more rows to fetch (from php.net).
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if($results) {
$row = mysql_fetch_array($results);
if($row) {
do {
echo "<p>{$row[whatever]}</p>";
} while($row = mysql_fetch_array($results));
} else {
echo "<p>No results found</p>";
}
} else {
echo "<p>There was an error executing this query.</p>";
}
Regardless of whether or not you actually use what you SELECTed, all of the rows are still returned. This is terribly inefficient because you're just throwing away the results, but you're still making your database do all of the work for you. If all you're doing is counting, you're doing all that processing for nothing. Your solution is to simply use COUNT(*). Just swap COUNT(*) in where you would have your SELECT statement and you're good to go.
However, this mostly applies to people using it as a complete substitute for COUNT. In your case, the usage isn't really bad at all. You will just have to manually count them in your loop (this is the preferred solution for SQLite users).
The reason being is in the underlying SQLite API. It doesn't return the whole result set at once, so it has no way of knowing how many results there are.
As explained on the mailing list you found. It is inefficient to return the count of rows because you need to allocate a lot of memory to hold the entire (remaining) result set. What you could do, is to simply use a boolean to test if you have output anything.
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
$empty_result = true;
while ($row = mysql_fetch_array($results)) {
echo "<p>$row[whatever]</p>";
$empty_result = false;
}
if ($empty_result) {
echo "<p>No results found</p>";
}
Just learning PHP and I'm having some trouble understanding mysql_query. My understanding is that mysql_query is supposed to return FALSE if the record is not found. However, it seems that it always returns true because "FOUND!" is always the result:
$q = "SELECT * FROM users WHERE username = 'doesnotexist'";
$r = mysql_query($q);
if (!$q) {
echo "<p>NOT FOUND!</p>";
} else {
echo "<p>FOUND!</p>";
}
mysql_close();
Thanks in advance for any light you can shed.
mysql_query returns false if there is an error, not if there are no results found. From the documentation:
For SELECT, SHOW, DESCRIBE, EXPLAIN
and other statements returning
resultset, mysql_query() returns a
resource on success, or FALSE on
error.
For other type of SQL statements,
INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success
or FALSE on error.
mysql_query() will also fail and
return FALSE if the user does not have
permission to access the table(s)
referenced by the query.
If you want to check to see if there were results returned by your query, use mysql_num_rows(). See the documentation:
Use mysql_num_rows() to find out how
many rows were returned for a SELECT
statement or mysql_affected_rows() to
find out how many rows were affected
by a DELETE, INSERT, REPLACE, or
UPDATE statement.
You are checking the '$q' variable (your sql statement) instead of the '$r' variable (the mysql result)
if (empty($r)) {
echo "<p>NOT FOUND!</p>";
} else {
echo "<p>FOUND!</p>";
}
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Ok i have worked out the answer to this.
This is the version for updating a database that tells you if a record was valid.
$updatequery = "update `mydb` set `userid` = '$arr[0]', `name` = '$arr[1]' where `age` = '$arr[2]'";
$updatequeryresult= mysql_query($updatequery);
$howmanyupdatedrecords = mysql_affected_rows();
if ($howmanyupdatedrecords == 0) {
echo("The update didn't update any records as no one matched an age of " .$arr[2]");
}
This will iterate through the DB updating all people with the specified age, if the age does not exist in the DB a message will be displayed showing you the age that does not exist. Also something to note, even if the mysql query matches a record, it won't update the record if the data already matches what it is being updated to. This causes the script to return "no one matched an age" even though there are people who did match. Can only attribute that to a bug in mysql. I told MySQL to update the information I don't see why it should take it upon itself to not bother doing as i told it. ;)
Your 'if (!$q)' should be 'if (!$r)' I think.
if that dosen't work, try this:
<?php
$q = "SELECT * FROM users WHERE username = 'doesnotexist'";
$r = mysql_query($q);
if (!mysql_num_rows($r) >= 1) {
echo "<p>NOT FOUND!</p>";
} else {
echo "<p>FOUND!</p>";
}
mysql_close();
?>