Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to select a value from the database. The select query is returning a 1 or 0. I want to echo 'yes' if the returned value is 1 and echo 'no' if the returned value is 0.
When I run the script I always get 'Yes'.
Does someone know what is wrong with my script?
Here is my PHP script:
$sql = "SELECT row FROM table WHERE id='". $_GET['id'] ."'";
$result = $conn->query($sql);
if ($result == 1){
echo 'yes';
}
else
{
echo 'No';
}
$conn->close();
For the answer it is important to know which Database API you use.
For most APIs
$result
will be a kind of result object which represents your result. Normally a collections of rows. You can call some kind of fetch function to get a row from a result, and then you would check whether this row contains 1 or 0.
You should read the documentation of your API for more details.
PHP gives always Yes, because the == Operator tries to do type conversion, and I suppose it converts both values to true.
http://php.net/manual/de/language.types.type-juggling.php
If you just want to know if the id exists, you can use a COUNT(*) expression. That way the query will be guaranteed to return exactly one row, whether the count is 0 or 1.
You should get into the habit of using parameters instead of creating SQL injection vulnerabilities by concatenating $_GET variables into your query.
And check for errors after every database function that may return an error.
$sql = "SELECT COUNT(*) FROM table WHERE id=?";
if (($stmt = $conn->prepare($sql) === false) {
error_log($conn->error);
die("Database error");
}
// assuming mysqli, but if you use PDO, binding is done differently
if ($stmt->bind_param('i', $_GET['id']) === false) {
error_log($stmt->error);
die("Database error");
}
if ($stmt->execute() === false) {
error_log($stmt->error);
die("Database error");
}
if (($result = $stmt->get_result()) === false) {
error_log($stmt->error);
die("Database error");
}
$row = $result->fetch_row();
$count = $row[0];
if ($count >= 1){
echo 'yes';
}
else
{
echo 'No';
}
$stmt->close();
$conn->close();
Related
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 1 year ago.
The question is simple, I have a small database and what I would like to compare is a specific column.
Scenario:
Using PHP to get the result from a querie and getting the value:
$sql = "SELECT verified FROM user WHERE id = ?";
$stmt->bind_param("i", $id);
$stmt->execute();
verified is a tinyint, either 0 or 1.
So how using PHP could make an if statement which compares either the result of $stmt->execute(); is 0 or 1.
<? php if(mysqli_fetch_row($stmt) == 0) {
echo "Not verified"
} else {
echo "Verified"
}
PD: What I would like to know is how to compare and operate on a SQL query.
You are almost there, jus grab result, and then compare it:
$result = $stmt->get_result();
$row = $result->fetch_array(MYSQLI_ASSOC);
if($row['verified'] == 1){
echo 'verified';
}else{
echo 'not verified';
}
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I an trying to query a mySQL database using a PHP function. Intermittantly, the function that I am using does not seem to return a result. As far as I can detect, it's not a null response, and based on the function, it doesn't seem to be returning an invalid result ( the return string Nuthin in this case ).
function GeneratePiece2 ($sqlstr){
$conn = new mysqli(gHOST, gUSER, gPASSWORD, gDATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sqlstr);
$returnable = "";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row;
$returnable = $row;
}
} else {
return "nuthin";
}
$conn->close();
return $returnable;
}
I've been using the same SQL Query of
SELECT Name FROM Char_Name_full WHERE Male=1 AND DivisionID=12 ORDER BY RAND() LIMIT 1
Around 80% of the time I will receive a result of something like {"Name":"Christoph"} but 1 out of 10 returns nothing.
If someone is having problems with fetch_assoc() returning "Undefined index":
Check the indexes names (database Column name) - they are case sensitive.
Example:
For "SELECT Name FROM..." Your code must be $row["Name"]. Not NAME or name.
In your query, you are checking if the number of rows is greater than zero, but you are not doing anything to check if the value that is returned is Null. The behaviour that you are describing matches the scenario of at least 1 row in 'Name' that has a NULL value.
Note that I am not going to comment on your code structure or syntax here, but I have changed your response values to help identify / prove that a null value is the issue here.
Also, if your query is limited to a single row, then the while loop will only iterate once.
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// Echo out the values for Name in the result set
if(is_null($row["Name"], ))
echo '[NULL]';
else
echo $row["Name"];
// your application logic ;)
$returnable = $row;
}
} else {
return "no rows";
}
Please consider using a SQL IDE like Toad for MySQL along side your development, then you can visually inspect your data for these issues without writing code hacks :)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So I have this code:
<?php
if (!isset($_GET['email']) && !isset($_GET['key'])) {
echo 'NOT ALLOWED TO ACCESS PAGE';
}
if (isset($_GET['email']) && isset($_GET['key'])) {
$email = $_GET['email'];
$regKey = $_GET['key'];
$query = mysql_query("SELECT * FROM `users` WHERE `email`='$email' AND `regRandom`='$regKey'");
if ($query == $regKey) {
mysql_query("UPDATE `users` SET `activated`=1 WHERE `email`='$email'");
if (mysql_query("SELECT activated FROM users WHERE activated='1'")) {
echo file_get_contents("http://TheMegaHouse.com/pageContent/head.php");
echo file_get_contents("http://TheMegaHouse.com/pageContent/notLoggedIn/topNavBar.php");
echo file_get_contents("http://TheMegaHouse.com/pageContent/header.php");
echo 'PASSED';
footer();
} else {
activationFail();
}
} else if ($regKey !== $query) {
echo 'FAIL';
}
}
?>
The thing is that in my database, the value that is in the regRandom column is in fact equal to the value in the key variable in the url but for some reason it is echoing out "FAIL" instead of "PASSED".
Any suggestions on what I am doing wrong, a better way of doing what I want to do or any suggestions?
Always read manual first:
http://php.net/manual/en/function.mysql-query.php
This line of code:
mysql_query("SELECT * FROM `users` WHERE `email`='$email' AND `regRandom`='$regKey'");
Is returning you resource, instead of variable you are lookng for.
Small fix for you:
list($regRandom) = mysql_fetch_row(mysql_query("SELECT regRandom FROM `users` WHERE `email`='$email' AND `regRandom`='$regKey'"));
if ($regRandom == $regKey) {
// magic
And another two things:
mysql_* functions are deprecated
i strongly recommend you to read about SQL Injections.
You should not be using the deprecated mysql_* functions but switch to PDO or mysqli and prepared statements.
However, the problem you are having is that you are comparing a resource to a sent-in variable.
My guess is that $regKey is an integer and $query is the result of a mysql query. You need to fetch a row from the result-set and compare a specific value from that row to your $regKey.
Correct me if Im wrong, but $query results is a resource? You haven't done anything with it.
I would suggest just doing a simple mysql_num_rows() check like this:
$query = mysql_query("SELECT * FROM `users` WHERE `email`='$email' AND `regRandom`='$regKey'");
if (mysql_num_rows($query) == 1) {
Its pointless to check again because you are already checking in the SQL query :) So simply check the number of rows returned. 0 = not found, 1+ = results :)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Function
public function isUsernameAvailable($username) {
$sql = "SELECT COUNT(*) FROM users WHERE username = '$username'";
$sql = $this->db->quote($sql);
if ($sth = $this->db->query($sql)) {
if ($sth->fetchColumn() > 0) {
return false;
} else {
return true;
}
}
}
if (!$user->isUsernameAvailable($_POST['username'])) {
echo 'The username is already taken!';
$error = 1;
}
I get the output "The username is already taken!" even though It isn't.
select count(*)... will ALWAYS return a record, even nothing is matched
so, you can try this :
select 1 from ...;
between, a proper method to check any record return should be using rowCount
as indicate by the rest :-
you should make use of bind rather than using quote
function should always return a value
Your isUsernameAvailable function will return NULL (equals to FALSE) when the query fails. This will trigger the The username is already taken! message.
Looks like your SQL query always fails, which I think is no wonder because you blindly apply quotes onto it.
After running a SQL query, you must more properly deal with the case that the query failed, e.g. display that an internal SQL error occured and log it, so you can look into the log and locate the cause of the error.
Additionally, you should use the PDO more properly, specifically when you want to prevent SQL injection (which you must care about). See Best way to stop SQL Injection in PHP.
Use rowCount() instead of fetchColumn()
if ($sth->rowCount() > 0) {
fetchColumn returns false if there is no column and also see ajreal answer.
if ($sth = $this->db->query($sql)) {
if ($sth->fetchColumn() == false) {
return true;
} else {
return false;
}
}
Can you try using the following code?
$st->rowCount() > 0
$sql = "SELECT COUNT(*) FROM users WHERE username = '$username'";
$sql = $this->db->quote($sql);
You are quoting the whole query, this does not make any sense and is outright dangerous from a security standpoint – and probably results in an invalid query anyway.
Here's a more proper code:
// return TRUE if user is available
public function isUsernameAvailable($username) {
$sql = "SELECT id FROM users WHERE username = :username";
$stmt = $this->db->prepare($sql);
$stmt->execute(array(':username' => $username));
return $stmt->fetch() === FALSE;
}
if (!$user->isUsernameAvailable($_POST['username'])) {
echo 'The username is already taken!';
$error = 1;
}
I am trying to stop the mysql_query error from being output onto my form. Currently if there is no location found, I receive the error
"Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 11"
I am trying to catch this error, and instead assign the $location variable to not found. My code for attempting this is below, what am I doing wrong?
Thanks!
$query3 = "SELECT `location` FROM location WHERE vin = '$vin' LIMIT 1";
$result3 = mysql_query($query3);
if (!mysql_result($result3,0)) {
$location = "Not found";
} else $location = mysql_result($result3,0,0);
mysql_result() generally shouldn't be used. You'd be better off with something like:
$result3 = mysql_query($query3) or die(mysql_error());
if (mysql_numrows($result3) == 0) then
$location = "not found";
} else {
$row = mysql_fetch_array($result3);
$location = $row[0];
}
Your error is caused by the fact that the query returned no rows - e.g. nothing matched. You then tried to retrieve the first field in the first row of that result set, a row which doesn't exist. Checking the number of returned rows with mysql_numrows() is safer, as that works whether the query found nothing or a bajillion rows.
You should look into how to set your error and warning levels in php ini - usually you want a s little output on prod as possible.
http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting
However, here, the code that would generate that error is:
$result3 = mysql_query($query3);
That is the line you should be writing your if or "or die" statements around:
$result3 = mysql_query($query3)or die($location = "not found");
You should look into using OOP; using a database class to handle interaction with your DB.
But, basically you want to check if there are any rows, before trying to bring back the results.
Try checking with "mysql_num_rows" in your "if" statement:
if (!mysql_num_rows($result3)) {
First, you can add #:
if (!#mysql_result($result3,0)) {
$location = "Not found";
} else $location = mysql_result($result3,0,0);
Second, you can check mysql_num_rows(result3) before mysql_result call.
Mysql_query returns false if nothing is found so a simple :
$result3 = mysql_query($query3);
if (mysql_affected_rows($result3) == 0) {
$location = "Not found";
} else $location = mysql_result($result3,0,0);
Should do it.