PHP mysql result issue - php

I have this line in my registration page.
if (device_id_exists($_POST['device_id']) == true) {
$errors[] = 'Sorry the Serial Number \'' . htmlentities($_POST['device_id']) . '\' does not exist.';
}
I have this in my function page.
function device_id_exists($device_id) {
$device_id = sanitize($device_id);
$query = mysql_query("SELECT COUNT(`numbers`) FROM `devicenumbers` WHERE `numbers` = '$numbers'");
return (mysql_result($query, 0) == 0) ? true : false;
If I run this query SELECT COUNT(numbers) FROMdevicenumbersWHEREnumbers= '1234567890'
(a valid number) it will return 1 = match found right? If I put a bogus number it returns a '0'.
What is happening is when there is a valid number it still returns the error the number doesn't exist. If I change it to the result to == 1 it will submit any number? Im a newbie to DB calls any help appreciated. I hope I provided enough info.

Looks like you're calling the incorrect variable. Within the device_id_exists() function, you're accepting a variable named $device_id. However when you're performing the query, you're calling what appears to be an undefined variable: $numbers. I suspect $numbers should be renamed to $device_id.
I see your $device_id comes from a form post. I'd HIGHLY recommend you escape the variable, using mysql_real_escape_string() to ensure you are protected against SQL injection. Please note that sanitize() does NOT protect against SQL injection!
On one additional note, I'd recommend utilizng mysql_num_rows() rather than mysql_result() because mysql_result() actually asks the database server to return an actual result when all you really care about is whether the entry exists or not, not it's actual value.
function device_id_exists($device_id) {
$device_id = sanitize($device_id);
$device_id = mysql_real_escape_string($device_id);
$query = mysql_query("SELECT COUNT(`numbers`) FROM `devicenumbers` WHERE `numbers` = '$device_id'");
return mysql_num_rows($query) ? True : False;
}

I had a similar problem with mysql result set , It returns nums_rows == 1 even when there are no records (while using max() inside select query - In your case you have used count())... Instead of checking mysqlquery to 0, check it whether the result set empty (That's how i solved my problem).. eg. if(!empty(mysql_result($query))) ? true : false;

Related

PHP - Can if-statement being ignored/skipped for some reason?

What I want to achieve : if a user pass a PHP parameter to the server, it will return the same parameter value back to the user, instead of returning the value from the database itself.
while($row = mysqli_fetch_assoc($result)){
$classId = $row['classId'];
if($obj['classId'] != ""){
$classId = $obj['classId'];
}
...
}
For some reason, I found out that the $classId still using the $row['classId'] value, even if the user had inserted the classId parameter. It seems that the PHP has ignored/skipped the if statement.
if($obj['classId'] != ""){..} //SKIPPED?
The code works fine right now and I do get the return of the same parameter value. Only one user out of hundreds got this issue and I assumed that the he/she had sent the parameter when the server was busy.
Questions:
1.Can if-statement being ignored/skipped for some reason?
2.How to make the if-statement more reliable even if the server in a high-traffic?
Excuse me for posting here. I don't find the right keywords for googling myself.
Thank you.
You could try having your if statement more strict.
if($obj['classId'] != ""){
$classId = $obj['classId'];
} else {
$classId = $row['classId'];
}
I'd also recommend using isset instead of checking for an empty string.
if(isset($obj['classId'])) { }

My function returns true when I expect false

I am confused as to why my code returns true when I expect false and the other way around. Here's my code:
public function CheckMac($mac){
$database = new Database();
$db = $database->connectDatabase();
$checkedmac = $db->prepare("SELECT * FROM `displays` WHERE `displayMac` = '$mac'");
$checkedmac->execute();
$count = (int)$checkedmac->fetchColumn();
if ($count > 0) {
return true;
} else {
return false;
}
}
I have the query right, when I echo $macand put it inside the query, phpMyAdmin gives me back the expected line, since it exists in the database, but when I run this code, I'm getting a false return.
Where did I go wrong on this one?
There is a fantastic yet underestimated answer, If your code is doing something unexpected, there's a good chance you're making an assumption somewhere.
You are yet to learn the cornerstone concept in the art of programming called debugging. Which means you are supposed to verify every single assumption you made.
You are assuming here that when a query returns a row, the (int)$checkedmac->fetchColumn(); statement returns a positive number. So you have to verify it.
I can make an assumption that the first column in your table does not contain a positive number but rather a string. A string cast a number will return 0. It will explain why you're getting 0 when a record is found. But you have to verify it as well.
If my assumption proves to be true, simply select a constant value instead of rather uncertain *. You can use 1 for example, and your query will work flawlessly:
public function CheckMac($db, $mac){
$stmt = $db->prepare("SELECT 1 FROM `displays` WHERE `displayMac` = ?");
$stmt->execute([$mac]);
return $stmt->fetchColumn();
}
A couple notes:
you should always connect only once. Create a $db variable beforehand in a single place and then use it everywhere
you are using a cargo cult prepared statement that protects from nothing. It should be always the way shown in my example.
if ($count > 0) return true is a tautology. A $count > 0 statement already returns true or false, so you can return its result rigtht away, without a superfluous condition
moreover, 1 is as good as true in PHP. So in the end you can return the result of fetchColumn() right away. in case the row is found it will be 1 equal to true and just false otherwise.

SELECT COUNT(*) returns 1 even if the request should return 0

When I'm trying to get the number of rows on a SQL request and if not, the connection that follow fails.
But in any case (also if the request should return 0), it returns 1.
Here's my code :
$str = 'SELECT count(*) FROM admins WHERE mail = ? AND mdp = ?';
$arr = array($mail, $pass);
$rqt = sendRqt($str, $arr);
$tab = $rqt->fetchColumn();
$cnt = count($tab);
echo $cnt;
I don't understand why there's no time it returns 0
The problem is the use of the php function count().
You already have the correct number in your $tab variable as a string (probably, depends on php configuration / version) so you can echo it or cast it to an integer to make sure it is a number.
However, in php:
count(0) === 1
count('0') === 1
See here for example.
You should remove count($tab).
the SQL "COUNT(*)" allways returns a row with the count (quantity) of values, so if you apply the php count() function, always will return 1 because there is one row that contains the value of the COUNT sql function
I believe COUNT() needs a column name.WRONG!! count(*) should count all rows, but I still reccomend a column name like id or something. You could also use an AS to make life a little easier
$str = 'SELECT count(`COLUMNNAME`) AS cnt FROM table WHERE ....

Why is my php "if statement" not affecting my mysql query?

First of all, I know mysql is deprecated. Will change to mysqli as soon as I figure out the issue at hand. My query continues to update all my rows even if the data is not set in the 'stripetoken' column. Why is this happening?
Code snippet:
$token_query = 'SELECT * FROM jobsubmission';
$token_res = mysql_query($token_query);
$token_row = mysql_fetch_array($token_res);
if(isset($token_row['stripetoken'])) {
$updqry = 'UPDATE jobsubmission SET assigned=1 WHERE ID="'.$book_ids[$jcount].'"';
$update = mysql_query($updqry);
$bookdate = date("d-m-Y");
Because $token_row['stripetoken'] is always set because it is a column in your database and it will be available in $token_row as a result. Now whether it has a value or not is a different story. You should be using empty() instead (assuming you don't want it to be true for falsy values).
if(!empty($token_row['stripetoken'])) {
So while #JohnConde was absolutely correct in saying I needed to use the empty function over the isset, my solution layed elsewhere. Here is how I managed to get the query to work to my specifications:
instead of searching for empty, I made the 'stripetoken' column NULL
by default.
This allowed me to use the following code:
$token_query = 'SELECT * FROM jobsubmission WHERE ID="'.$book_ids
[$jcount].'" and stripetoken is not null';
$token_res = mysql_query($token_query);
$token_row = mysql_fetch_object($token_res);
if(!$token_row->stripetoken == NULL) {

Mysqli query returns an emptry string

I'm dealing with an issue where the mysqli library in PHP doesn't seem to return a longtext column. I can get the value of the column using both console and PHPMyAdmin but mysqli returns nothing but an empty string.
Here's the function I'm using:
public function greetings_get() {
$output = array();
$greetings_query = "SELECT `engagement_data`.`data`, `engagement_users`.`name` FROM `engagements`, `engagement_data`, `engagement_users` WHERE `engagements`.`promo_slug` = 'stod2.hm2013' and `engagements`.`user_fbid` = `engagement_users`.`fbid` and `engagement_data`.`engagement_id` = `engagements`.`id` ORDER BY RAND() LIMIT 0,5";
$greetings = $this->db_connection->prepare($greetings_query);
$greetings->execute();
$greetings->bind_result($gr_data, $gr_name);
while ($greetings->fetch()) {
$output[] = array('message' => $gr_data, 'name' => $gr_name);
}
return $output;
}
In this case, $gr_data is an empty string, while $gr_name returns a value. –Strange isn't it?
Is there something I'm doing wrong?
According to this answer at php.net, you must use mysqli_stmt::store_result before you bind the result
When using prepare to prepare a statement to retrieve LOBs the method order matters.
Also, method 'store_result()' must be called and be called in correct order.
Failure to observe this causes PHP/MySQLi to crash or return an erroneous value.
This
$greetings->execute();
$greetings->store_result();
$greetings->bind_result($gr_data, $gr_name);
should fix it.

Categories