Check mysqli result if row already exists - php

I'm trying to check if a row exist in my db like this:
$uid = $_GET['queryString'];
if(isset($_GET['queryString'])) {
echo "New: ".$uid."<BR>";
$query = "SELECT * FROM stuff WHERE $uid";
// Escape Query
$queryE = $db->real_escape_string($query);
$results = $db->query($queryE);
if(($results->num_rows) > 0) {
echo "NO!";
}
else
{
echo "Make new row";
}
}
else
{
echo 'Error!';
}
But I keep getting the error: Trying to get property of non-object in ....
So if it exist I do one thing, if it doesn't I do the other, i've been searching for about an hour to find the cause, maybe I'm mixing up old PHP4 with my PHP5 stuff?
I've tried a lot, tried some examples but tend to get the error: mysql_fetch_array() expects parameter 1 to be resource, string given
Or should I check it in the query itself?

What line is the error on?!
If it is on the real_escape_string line, you haven't instantiated $db properly.
If it is on the $results->num_rows line, try changing
$results = $db->query($queryE); to:
if(!($results = $db->query($queryE))) {
echo 'Make new row';
} else {
// user likely exists, check $results
}
Also, you need to clean up the way you check the query string -- just process the query variable you want, rather than the whole string. Suggest also to use a different name for the query variable and the table column.

Related

fetch_assoc mysqli returning empty [duplicate]

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 :)

Query empty if included

I have been performing a query inside my page -- say, page.php -- where I run a simple query.
Pseudo-code:
$request_unavailble = mysqli_query($mysqli, "SELECT * FROM my_table WHERE availble='0'");
When this is performed from within page.php, I get all results where availble is set to 0. However, if I run this from within a seperate included file, the data returns empty. In fact, mysqli_num_rows returns 0 when included.
What's going wrong, here?
Edit
The following function was added as an include (both as a function and alone)
function compte_messagerie()
{
$requetes_messagerie = mysqli_query($mysqli, "SELECT * FROM ".DB_PREFIX."messagerie WHERE lu='0'");
if(mysqli_num_rows($requetes_messagerie) == 0)
{
echo '<a id="messagerie" href="messagerie">'.AUCUN_NOUVEAU."</a>";
}
else if(mysqli_num_rows($requetes_messagerie) == 1)
{
echo '<a id="messagerie" href="messagerie">';
echo '<span>'.mysqli_num_rows($requetes_messagerie)."</span> ";
echo MESSAGES_SINGULIER."</a>";
}
else
{
echo '<a id="messagerie" href="messagerie">';
echo '<span>'.mysqli_num_rows($requetes_messagerie)."</span> ";
echo MESSAGES_PLURIEL."</a>";
}
}
When porting your query into a function, the MySQLi connection object in $mysqli went out of scope, and was therefore invalid inside the function. With display_errors enabled, I would expect you to see errors like:
Notice: undefined variable $mysqli
Warning: mysqli_query() expects parameter 1 to be resource, null given
The cleanest solution is to pass $mysqli into your function as a parameter, making it available to the function's scope
// Expect the MySQLi resource as a parameter...
function compte_messagerie($mysqli)
{
$requetes_messagerie = mysqli_query($mysqli, "SELECT * FROM ".DB_PREFIX."messagerie WHERE lu='0'");
if(mysqli_num_rows($requetes_messagerie) == 0)
{
echo '<a id="messagerie" href="messagerie">'.AUCUN_NOUVEAU."</a>";
}
// etc.....
}
Try this. Please check if the available table is require string value or integer.
$request_unavailble = mysqli_query("SELECT * FROM my_table WHERE availble= 0 ");
while($rows = mysqli_fetch_assoc($request_unavailble)){ // <- this will check if there some data fetch
// You put some code here
}

Codeigniter function returning an empty query

I have this function on my model, which receives a parameter so I can pre-load some information on the view page, but somehow is coming back empty:
function addTicket($idt)
{
//Db Connection
$DB2 = $this-> load-> database('DB2', TRUE);
if (!empty($idt)){
$query = $DB2->query ("
Select TROUBLE_ID, ASSIGNED_DATE, CREATOR, PROBLEM_DESCRIPTION, RESOLUTION, RESOLVED_DATE
FROM TABLE1
WHERE TROUBLE_ID = ".$idt."
");
if($query){
return $query->result_array();
}
else
{
echo 'No Queries to display';
}
}
else {echo 'No results to display';}
}
I have an Oracle DB with a ton of entries, but the query keeps coming back empty, Just in case I did an echo 'id:'.$idt.; to check if the ID is being passed. And yes it is.
Also Im getting this message:
Fatal error: Call to a member function result_array() on a non-object
On my view page i have this code:
foreach($results as $row){ }
And im getting this message now:
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Any idea why this is not working?
Is this CodeIgniter? If so a better way to check for results is if($query->num_rows() > 0) { } rather than just if($query) { }
Also if its CodeIgniter make sure you have db_debug set to TRUE in the config/database.php otherwise you won't get to see the database errors.
For some reason the query is failing
$this->db->_error_message();
should tell you why
$this->output->enable_profiler(TRUE);
Should give you much more information about the query
Update:
$DB2 = $this-> load-> database('DB2', TRUE);
if (!empty($idt)){
$query = $DB2->query ("
change ^^ to vv
$DB2 = $this-> load-> database('DB2', TRUE);
if (!empty($idt)){
$query = $this->DB2->query ("
Finally I was able to fix this problem when in my query condition i used single quotes before double quotes, like this:
Select TROUBLE_ID, ASSIGNED_DATE, CREATOR, PROBLEM_DESCRIPTION, RESOLUTION, RESOLVED_DATE
FROM TABLE1
WHERE TROUBLE_ID = '" . $idt . "'

Catching mysql_query error

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.

How do I find out if no results are returned from a mysql_query w/out dieing

I am grabbing the time from a list of ids. Not every id has a time associated with it.
How can I tell if there are no results (EG ID is not in the table yet) and then not get lots of Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 9 in /home/aslum/... errors...
$tquery = "SELECT time ".
"FROM clicks ".
"WHERE id LIKE '".$id."'";
$tresults = mysql_query($tquery) or die (mysql_error());
// What do I do here?
// IF $TRESULTS == "" THEN $foobar = false else $foobar = true
$clicktime = mysql_result($tresults,0);
if ($foobar==true) echo $clicktime."<br>";
if(mysql_num_rows($result) > 0) {
// do something
}
Here's a slightly more verbose way to see where things are going wrong, using mysql_errno and mysql_num_rows to provide more information.
$sh = mysql_query($sql);
if($sh === false) {
$error = mysql_errno();
if($error) {
// You really should be logging this instead of just calling die.
die(mysql_error());
}
// Otherwise, the query just didn't return a result set for some reason...
echo "Something bad and unexpected happened.";
}
// Now the fun part.
if(mysql_num_rows($sh) > 0) {
echo "I got rows!";
} else {
echo "I got nothin' :(";
}
(Also, please use the mysqli or PDO extensions instead of mysql if you can.)

Categories