Quering integer in MySQL over PHP - php

I'm working with a table ("Item") which has the field "Aprovado" and it's an integer that checks if the item is approved or not (1 for yes, 0 for no) (not my table, I would have chosen proper boolean).
I know there are items there, and I know there are lots of items with "Aprovado" set to 1. (I am successful with queries "SELECT * FROM Item ORDER BY ItemID ASC")
yet, when I do:
mysql_select_db($theDatabase, $db) or die("Could not find database.");
$query = "SELECT * FROM Item WHERE Aprovado = 1";
$resultID = mysql_query($query, $db) or die("Data not found.");
It just returns "Data not Found." What's wrong?

Could try changing your die(...) into:
die('Invalid query: ' . mysql_error());
That will show you the actual MySQL error.

mysql_query does not return FALSE if the query returns no data. It only returns false on an error condition:
$result = mysql_query($query, $db) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
die("Data not found");
}
$row = mysql_fetch_assoc($result);
$resultID = $row['resultID'];

Related

second mysqli_query fails

the first query is fine but the second one wont work it just dies.
I plug the $city variable into the second one and echo it back and it shows the correct
value but its the the actual:
$row = mysqli_query($dbc, $query)
or die('Error while querying the Database');
that fails... please help!
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or WriteMessage('Error', 'Could not connect to the Database...');
//get user city...
$userID = $_SESSION['userID'];
$queryUserCity = "SELECT * from user where userID = $userID";
$GetResult = mysqli_query($dbc, $queryUserCity)
or die('Error while querying the Database');
$getRow = mysqli_fetch_array($GetResult);
$city = $getRow['city'];
$state = $getRow['state'];
$username = $getRow['username'];
echo 'username='.$username.' ';
echo 'city='.$city;
echo 'state = ' .$state;
$query = "SELECT * FROM adds where city = $city ORDER BY addDate ASC";
//fails right here...
/*-->*/ $row = mysqli_query($dbc, $query)
or die('Error while querying the Database');
echo $query;
exit();
while($row = mysqli_fetch_array($data))
{
You are trying to find a string without single quote. You use integer without single quote but in case of string you have to use single quote with your string.
change
$query = "SELECT * FROM adds where city = $city ORDER BY addDate ASC";
to
$query = "SELECT * FROM adds where city = '$city' ORDER BY addDate ASC";
and to find out exact error try to use the below code.
if (!mysqli_query($dbc, $query)){
echo("Error description: " . mysqli_error($dbc));
}
If the city is a textual type (and it probably is), you'll need:
... where city = '$city' ...
But, in fact, you shouldn't really be doing it that way anyway, since it opens you up to the possibility of SQL injection attacks if someone can enter arbitrary text for their city.
You should start looking into parameterised queries since they can protect you from such attacks. See Exploits of a Mom and the invaluable explain-xkcd entry.

AJAX Called PHP Query Not Working

I'm attempting to display dynamic data in a Bootstrap Modal using an AJAX call to a PHP query. The Javascript function is working fine and passing the ID to be used in the .php file, but the query itself doesn't seem to be working. I must be missing something pretty simple, but I don't get why it isn't working.
SQL / PHP
This file is being called and appears to be connecting to the db correctly, but the query itself isn't working.
$q = intval($_GET['q']);
$con = mysqli_connect('omitted','omitted','omitted','omitted');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT * FROM Orders WHERE orderID = '".$q."'";
$result = mysql_query($con, $sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
No result is being returned, and no error message is coming back. A var_dump of all the variables used in this query returns the following: (When the die conditional is removed)
var_dump($q) = int(3)
var_dump($sql) = string(40) "SELECT * FROM Orders WHERE orderID = '3'"
var_dump($result) = bool(false)
It has nothing to do with AJAX. You are mixing mysql and mysqli.
Try the following -
$sql = "SELECT * FROM Orders WHERE orderID = '".$q."'";
$result = mysqli_query($con, $sql);
if (!$result) {
die('Invalid query: ' . mysqli_error());
}

PHP, resource id# instead of actual string

I have run across a problem during my query service to add a row in an online database in PHP. The addition of the row works just fine. I get user id and book id from the url and fetch the names of the book and the user to put into the row which i add to my third and last table.
When I get the names, put them in an array, json encode it and then echo it, it works. But when I put them in the row it prints resource id#3 and resource id#4 instead of the names.
Any ideas?
Here is my service:
<?php
$con = mysql_connect("localhost","root","root");
$userid=$_GET['uid'];
$id = $_GET['bookid'];
$type = $_GET['type'];
$zero = '0';
$one = '1';
$date = date("Y-m-d");
$arr = array();
if (!$con)
{
die('Could not connect: ' . mysql_error());
echo "error connection";
}
mysql_select_db("Jineel_lib",$con) or die("Could not select database");
$bkName = mysql_query("SELECT Name from books where ID='".$id."'");
$userName = mysql_query("SELECT Name from people WHERE User_ID='".$userid."'");
while($obj = mysql_fetch_object($userName))
{
$arr[] = $obj;
}
echo json_encode($arr);
if($type == 'borrow')
{
$query="UPDATE books set Availablity = '".$zero."' where ID= '".$id."' ";
mysql_query($query) or die (" borrow operation failed due to query 1");
$query1="INSERT into borrowed (BookID, BookName, BorrowerID, BorrowedName, DateBorrowed, Extended, Returned) values('".$id."','".$bkName."','".$userid."','".$userName."','".$date."','".$zer‌​o."','".$zero."')";
mysql_query($query1) or die (" borrow operation failed to due query 2");
echo "borrow success";
}
else if($type=='return')
{
$query="UPDATE books set Availablity = '".$one."' where ID= '".$id."' ";
mysql_query($query) or die (" return operation failed");
$query1="UPDATE borrowed set Returned = '".$one."' where BookID= '".$id."' ";
mysql_query($query1) or die (" return operation failed 1");
echo "return success";
}
else
echo "invalid parameters";
?>
THANK YOU IN ADVANCE
You don't actually retrieve the userName value here:
$userName = mysql_query("SELECT Name...
$userName is just the result resource object returned from the query. You do use mysql_fetch_object later on, which is appropriate, but then you try to use the actual result resource in your insert query:
$query1="INSERT into borrowed ...
It gets converted to the string you see. Instead, you need to use $obj->Name (you fetch the result into $obj, and presumably there is only one result). If there is more than one possible result, you will have to do that in a loop.
Listen to all of the comments on your question.

Adding either DISTINCT or GROUP BY to my mysql_query is causing no values to be returned

I am using php to get records from a mysql database using the following code:
<?php
$username="";
$password="";
$database="";
$hostname="";
$con = mysql_connect($hostname, $username, $password);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
if(isset($_POST['emp'])){
$emp = $_POST['emp'];
$result = mysql_query("SELECT * FROM contact_log", $con);
echo mysql_num_rows($result);
die();
while($row = mysql_fetch_array($result)){
$emp = $row['emp'];
echo $emp.'<br>';
}
die();
}
mysql_close($con);
?>
This works fine and returns the correct fields. The problem is that if I change the query to
$result = mysql_query("SELECT DISTINCT * FROM contact_log", $con);
or
$result = mysql_query("SELECT * FROM contact_log GROUP BY emp", $con);
no results are returned.
mysql_num_rows does not even return a value which indicates to me that those lines are breaking my code but I am unable to figure out how.
I doubt you want to do a distinct * on your first query. Looking at your code, you probably want:
"SELECT DISTINCT emp FROM contact_log"
And you can get more information about what is going wrong with mysql_error:
mysql_query("select * from table") or die(mysql_error())
Finally, are you sure that $_POST['emp'] is being sent? Put an echo right after that if to make sure. And just so you know, you aren't using the emp POST variable for anything other than a flag to enter that block of code. $emp = $_POST['emp']; is doing absolutely nothing.

$result equals nothing if mysql column not found?

How could i get $result too equal nothing if the column doesn't exist in PHP?
I was thinking something like this:
$result=mysql_query("SELECT * FROM users WHERE username=$key DESC LIMIT 1")or die ($result = '');
But i was told thats wrong.
It's wrong because you're killing the script with die when a DB error occurs, rather than doing stuff when you find no row.
What you presumably need is more like:
$result = mysql_query($query);
if ($result) {
if ($row = mysql_fetch_assoc($result)) {
// do stuff with row
} else {
// do stuff without row
}
} else { // not needed but left here for illustration purposes
// this is the part that would occur, had you called mysql_query(...) or die;
die(mysql_error());
}
$result=mysql_query("SELECT * FROM users WHERE username= '$key' LIMIT 1")or die (mysql_error());
then check the result of mysql_num_rows()
If you mean that the result returns 0 rows, you can check with mysql_num_rows, like this:
$result=mysql_query("SELECT * FROM users WHERE username=$key DESC LIMIT 1");
if (mysql_num_rows($result) == 0)
$result = '';
Your code will set $result to '' if there's an error, in which case mysql_query returns false. It will also halt the code, since you're calling die(). An empty result set is not an error, however. In that case mysql_query returns a valid resource identifier with no rows. If I understand your question, this is what you want to do:
$result=mysql_query("SELECT * FROM users WHERE username=$key DESC LIMIT 1");
if (mysql_num_rows($result) == 0){
$result = '';
}
<?php
// Here I assume you're using PHP PDO
$pdo = new PDO("mysql:server=localhost;dbname=mydatabase", "root", "");
$result = $pdo->query("SELECT * FROM users WHERE username=$key DESC LIMIT 1");
$errorcode = $pdo->errorCode();
$errorinfo = $pdo->errorInfo();
// Columns doesn't exist
if($errorcode == "43072") $result = "";
// Other error...
else if($errorcode != "00000") die("MySQL Error: " . $errorinfo[2]);
?>

Categories