mysql_query() returns something strange - php

I want to select one field (MessageCounter) from my database. Its type is int(11). And I want to increase it.
Here's how I try to select it:
$q = "SELECT MessageCounter FROM " . TBL_USERS . " WHERE username = '$username'";
$result = mysql_query($q, $this->connection);
then I try to add 1 to it:
$messagecount = $result + 1;
$field = "MessageCounter";
$q = "UPDATE " . TBL_USERS . " SET " . $field . " = '$messagecount' WHERE username = '$username'";
return mysql_query($q, $this->connection);
And in the database it updates to 19. If I add other number instead of 1, say 3, I get 21. So the $result is somehow equal to 18.
HOWEVER, if I try to update the database with the same unchanged result - it updates the field to 0.
Does anyone have any idea what is happening?

You cannot add 1 to $result - first you need to fetch the value out of it:
$row = mysql_fetch_row($result);
$messagecount = $row[0] + 1;`
BTW - at this stage of learning, you should abandon the deprecated mysql_ functions and switch to mysqli or PDO instead. Do it right now.

mysql_query() returns a Resource and not a normal variable on which you can perform addition operation.
and as n-dru suggested you should switch to PDO or mysqli coz mysql extension is deprecated in PHP 5.5.0 and it's removed from PHP 7.0.0.
read here

Related

How to get number of rows returned by an SQL select query?

I would like to get the number of lines returned by a select query in PHP. I have the following code:
$connection = new mysqli($server_name, $server_login, $server_password, $dbName);
if (!$connection) {
echo "error";
die("Connection failed. ".mysqli_connect_error())
}
//...
$command = "SELECT player_id FROM Player WHERE player_login = '" . $login."' AND player_password= '".$password."' ";
$result = mysqli_query($connection, $command);
echo num_rows($result);
I also tried with mysqli_stmt_num_rows() and mysqli_num_rows() but my result is always null (no result actually).
Do you know why?
There are a few ways to get the number of rows returned, the most common ones are to run COUNT(*) in MySQL, but there's also mysqli_num_rows($result) (not num_rows() like you used, unless you created that function yourself). mysqli_stmt_num_rows() will only work when you're using prepare() instead of query().
In ordre to use COUNT(*) you have to run and fetch the query first, while mysqli_num_rows() is a constant returned by the MySQLiResult object, which you can use if the query didn't fail.
I modified the piece of code you've got to check if the query actually succeeded, mysqli_num_rows() won't work if the query failed.
$command = "SELECT player_id FROM Player WHERE player_login = '" . $login."' AND player_password= '".$password."' ";
if ($result = mysqli_query($connection, $command)) {
echo mysqli_num_rows($result);
} else {
/* Query failed */
echo "There was an error with the query: $command";
echo "<br />".mysqli_error($connect);
}
Or you can use COUNT(*), but then you'll have to fetch the results first.
$command = "SELECT player_id, COUNT(*) as cnt FROM Player WHERE player_login = '" . $login."' AND player_password= '".$password."' ";
if ($result = mysqli_query($connection, $command)) {
$row = mysqli_fetch_assoc($result);
echo $row['cnt'];
} else {
/* Query failed */
echo "There was an error with the query: $command";
echo "<br />".mysqli_error($connect);
}
You should also note that this query is vulnerable to SQL injection, you should learn how to use prepared statements with placeholders to protect yourself against that. The manual on prepare() is a good place to start with that.
You also seem to be storing passwords either in plain-text, or with poor methods (such as md5 or sha1). PHP offer's a built-in function, password_hash()/password_verify() which you should use. If you're below PHP version 5.5, these functions aren't native, but there's a compability pack which can be used instead.
As a final note, mixing object oriented and procedural code will technically work (as the procedural ones in reality call the object oriented ones), but it's considered bad practice. If you connect with an object, continue to use object-oriented code.
References
http://php.net/mysqli-result.num-rows
http://php.net/mysqli-stmt.prepare
http://php.net/password_hash
$command = "SELECT count(*) as numberofrecord, player_id FROM Player WHERE player_login = '" . $login."' AND player_password= '".$password."' ";
Very simple solution:-
Use $result->num_rows in below way:-
if ($result = $mysqli->query("SELECT player_id FROM Player WHERE player_login = '" . $login."' AND player_password= '".$password."'")) {
printf("Select returned %d rows.\n", $result->num_rows);
}
Reference:- http://php.net/manual/en/mysqli.query.php
Note:-
Meanwhile read prepared statement and use them to prevent your code from SQL Injection.
Also always use password hashing mechanism while storing the password (if you used plain password).

MySql statement returning incorrect results

I am trying to receive an Id from my user table.
I have:
$retrieve_id = "SELECT userid FROM tb_users WHERE username = '$username'";
$user_id = intval(mysql_query($retrieve_id));
The statement should return 1 since that is the value in the table. However, it returns 6 which is the length of the column name (userid). This happens when I'm querying other tables too.
How can I retrieve the value from the table ONLY?
You need to fetch the actual result from the query, either using mysql_result or mysql_fetch_*.
$result = mysql_query("SELECT userid FROM tb_users WHERE username = '$username'");
if (!$result) {
die('Could not query:' . mysql_error());
}
$user_id = mysql_result($result, 0); // outputs first row
Note that all mysql_ functions are deprecated and you should use mysqli_ or PDO. Your query is also open to SQL injection.
http://php.net/manual/en/function.mysql-query.php
mysql_query returns a resource not the value.
$retrieve_id = "SELECT userid FROM tb_users WHERE username = '$username'";
$result = mysql_fetch_assoc(mysql_query($retrieve_id));
$user = $result['userid'];
A) mysql_* is deprecated
B) make sure you're parameterizing your inputs
C) try this:
$result = mysql_query($retrieve_id);
$user_id=$result["userid"];
function mysql_query returns resource type for a select query. For results you have to use mysql_fetch_array or mysql_fetch_assoc functions.
$retrieve_id = "SELECT userid FROM tb_users WHERE username = '$username'";
$result = mysql_query($retrieve_id));
$row = mysql_fetch_assoc($result)) {
echo $row['userid'];
Check the php docs on mysql_query(). It actually returns a resource, not simply the value you are querying for.
But you shouldn't even be using mysql_query() as it's deprecated in PHP 5.5, and you don't want to have to redo your code when you upgrade, do you?
Instead, use mysqli_query(), which will return a mysqli_result object. Then from that object, you can retrieve the values you're looking for with fetch_field()

WHERE id_member = 1 doesn't work in MYSQL

Well I have that code:
$query="INSERT INTO ".$db_prefix."members (badges) VALUES ('$id_badge') WHERE id_member = '$user_id'";
And PHP drop me that error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id_member = '1'' at line 1
What can I do? :/
SORRY FOR EVERY PERSON WHO HAS REPLY TO ME I WAS WORNG WITH THE $QUERY, I HAVE EDITED TO THE CORRECT QUERY, NOW YOU CAN ANSWER ME. THANKS. :D
To every person that have voted me down, I'm starting in mysql... ¬¬
Try it like
$query="UPDATE ".$db_prefix."members SET badges = '$id_badge' WHERE id_member = '$user_id'";
You need to UPDATE the table not INSERT.And Try to avoid mysql_* statements due to the entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.
There are two other MySQL extensions that you can better Use: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql.
You can't use WHERE in INSERT INTO. Use UPDATE command:
$query = "UPDATE " . $db_prefix . "members SET badges = '" . $id_badge . "' WHERE id_member = '" . $user_id . "'";
You are doing wrong do not insert data just update it
#mysql_query("UPDATE ".$db_prefix."members SET badges = '".$id_badge."' WHERE member_id='".$user_id."'");
$query = "UPDATE '".$db_prefix."members'
SET badges=$id_badge
WHERE id_member =".$user_id;
try putting up below line:
$query = mysql_query("SELECT `badges` FROM ".$db_prefix." members WHERE `id_member` = ".(int)$id_del_usuario."");
your second query:
$query="INSERT INTO ".$db_prefix."members SET (badges) VALUES (".$id_badge.") WHERE `id_member` = ".$user_id."";

mysql_num_rows error, but database is updated

I have some PHP problems regarding my PHP code
I create function that update database, for changing password. Here's my syntax
function changePassword($username, $password, $salt){
$query = "UPDATE mt_user SET password = '". $password ."' , salt = '". $salt . "' WHERE username = '". $username ."'";
$result = mysql_query($query);
if ($result == false){
$num_rows = mysql_error();
} else {
$num_rows = mysql_num_rows($result);
}
mysql_close();
return $num_rows;
}
I try this function by create some script:
echo changePassword('user1','test','test_salt');
The database value is updated but, the function is showing some warnings
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in.....
What's wrong with the code? Because I don't see any errors.
mysql_num_rows() is the wrong function here because what is does
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set.
To see how many rows were changed, use mysql_affected_rows().
$num_rows = mysql_affected_rows();
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
for update and insert queries you need to use mysql_affected_rows. mysql_num_rows only works for select statement.
A little advice: replace mysql to mysqli. It's more secure. This example is with this one.
function changePassword($username, $password, $salt){
$query = "UPDATE mt_user SET password = '". $password ."' , salt = '". $salt . "' WHERE username = '". $username ."'";
$result = mysqli_query($connection,$query);
if ($result){
$num_rows = mysqli_affected_rows($connection);
} else {
$num_rows = mysqli_error($connection);
}
mysql_close();
return $num_rows;
}

Unknown column 'AG' in 'where clause

I'm getting this error the error(title) on such a simple query:
function getBranch($BranchID){
$query = "SELECT Branch FROM Branches WHERE BranchID = {$BranchID}";
$r = mysql_query($query);
if (!$r) echo "Failed Query: " . mysql_error();
else return mysql_result($r, 0);
}
I know the mysql_ functions are being deprecated and I know the Column 'Branches' does exist. The var $BranchID is 'AG' when called and I've checked, that is a valid value.
You should not be using the deprecated mysql_* functions. It's much better to use PDO and parameterized queries.
The specific problem with your query is that you are missing quotes around your string value:
$query = "SELECT Branch FROM Branches WHERE BranchID = '$BranchID'";
You should also ensure that you escape the value correctly with mysql_real_escape_string.
$query = "SELECT Branch FROM Branches WHERE BranchID = '" .
mysql_real_escape_string($BranchID) . "'";
Related
How can I prevent SQL injection in PHP?

Categories