My results from a postgress query statement has no values? - php

I am relatively new with using postgress, so I am trying to get results without using the PDO statements.
My code is as follows, now I successfully made a connection with the database, on execution my webpage has no results. On furthur inspection I noted that the while loop does not execute I know it is not a logical error with my query statement because I ran the same query on the database and it returned values.
I think the problem is in the while loop, but I cannot understand. This query on the database returned 43 results.
$query = "SELECT * FROM property WHERE latitude BETWEEN " .$lat1 ." AND " .$lat2 ." AND longitude BETWEEN " .$lng1 ." AND " .$lng2;
$result = pg_query($db, $query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
pg_result_seek($result,0);
while($myrow = pg_fetch_assoc($result)) {
echo "reached";
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['p_id'], htmlspecialchars($myrow['type']), htmlspecialchars($myrow['latitude']), htmlspecialchars($myrow['longitude']));
printf ("<br>");
Again to re-iterate, the results array is not empty because it does not throw an error message, I think there is an issue solely with the while statement.

Try adding qoutes(')
So:
$query = "SELECT * FROM property WHERE latitude BETWEEN '" .$lat1 ."' AND '" .$lat2 ."' AND longitude BETWEEN '" .$lng1 ."' AND '" .$lng2 . "'";
Let us know if it helped

Related

Page hangs on multi command mysqli php

So I'm pretty new to PHP and I'm mostly just struggling my way through it but I've hit a roadblock that I just can't get over.
My goal is to run a few commands to clear and update a standings table and then display the data in a table. I've got the table to display pretty much no problem but when I add the code in to update the table the page stops before it even displays the table and it's just a blank page, it wont even run any of the HTML.
Here's the PHP, I can provide the rest of the page code if needed.
http://pastebin.com/GZ3KcNXK
<?php
$con = mysqli_connect("localhost","uakronhv_admin","uakhvzdbadmin01","uakronhv_game1");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "DELETE FROM standings WHERE 1=1; ";
$sql. = "INSERT INTO standings (`pId`,`pName`,`pStarve`) SELECT p.pId, concat(p.pFirst," ",p.pLast), TIMEDIFF(NOW(),s.lastTag) FROM players p left join starve s on p.pId = s.zId; ";
$sql.= $mysqli_real_escape_string("UPDATE standings SET sStatus = "Human" WHERE sId NOT IN (SELECT DISTINCT taggedId FROM tags); "):
$sql.= $mysqli_real_escape_string("UPDATE standings SET sStatus = "Zombie" WHERE (sId IN (SELECT DISTINCT taggedId FROM tags)) OR (sId IN (SELECT DISTINCT taggerId FROM tags)); "):
$que=$mysqli_query($sql);
$sp = mysqli_query($con,"call updateStandings()");
$result = mysqli_query($con,"SELECT * FROM standings");
echo "<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Status</th>
<th>Since Last Tag</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td style=\"text-align:center\">" . $row['pId'] . "</td>";
echo "<td>" . $row['pName'] . "</td>";
echo "<td style=\"text-align:center\">" . $row['pStatus'] . "</td>";
if ($row['pStarve'] > '72:00:00')
echo "<td style=\"text-align:center\">Starved</td>";
else if
(is_null($row['pStarve']))
echo "<td style=\"text-align:center\">--</td>";
else
echo "<td >" . $row['pStarve'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I'm just going to point out where the faults are, which may very well fix your code. If it doesn't, then you will need to read up on the better tutorials.
Regarding this code block:
$sql. = "INSERT INTO standings (`pId`,`pName`,`pStarve`) SELECT p.pId, concat(p.pFirst," ",p.pLast), TIMEDIFF(NOW(),s.lastTag) FROM players p left join starve s on p.pId = s.zId; ";
$sql.= $mysqli_real_escape_string("UPDATE standings SET sStatus = "Human" WHERE sId NOT IN (SELECT DISTINCT taggedId FROM tags); "):
$sql.= $mysqli_real_escape_string("UPDATE standings SET sStatus = "Zombie" WHERE (sId IN (SELECT DISTINCT taggedId FROM tags)) OR (sId IN (SELECT DISTINCT taggerId FROM tags)); "):
$que=$mysqli_query($sql);
The concatenation is incorrect $sql. = those should read as $sql .= which is why you say that the DELETE part works but not the rest following that statement. Had you used or die(mysqli_error($con)) to mysqli_query() it would have signaled the error.
Then you're probably wanting to sanitize input using mysqli_real_escape_string() but that's not how that function works and you don't use a $ sign in front of that function.
It works like this:
$variable = mysqli_real_escape_string($con, $_POST['variable']);
Read up on the function:
http://php.net/manual/en/mysqli.real-escape-string.php
Then you're using $mysqli_query with a dollar sign in front of that function, it's just mysqli_query.
Then you're doing SET sStatus = "Human" that should be single quotes and not double quotes SET sStatus = 'Human' and do the same for the other one.
Having used error reporting and checking for DB error using/adding or die(mysqli_error($con)) to mysqli_query() would have signaled the errors.
Error reporting should have given you warnings such as Undefined variable... in regards to $mysqli_query and $mysqli_real_escape_string.
That should give you enough information to debug your code.
Blank page often means syntax error. Maybe it's the one in front of the INSERT statement?
$sql. = "INSERT INTO standings ...";
Try this one ;)
$sql .= "INSERT INTO standings ...";
Edit: And as mentioned in the comments, it's the first step in debugging. Forgot to say it directly.

if statement to check if mysql row exists, then selecting next query

I'm attempting to select a query to use based on the number of rows returned by a test result.
$id = mysql_real_escape_string(htmlspecialchars($_POST['id']));
$result = "SELECT FROM Notifications WHERE UserID=$id";
$r = e_mysql_query($result);
$row = mysql_fetch_array($r);
$num_results = mysql_num_rows($result);
$result = '';
if ($num_results != 0) {
$result =
"SELECT U.UserID,U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U, Notifications N " .
" WHERE U.LocationID=0 " .
" AND N.UserID='$id'";
} else {
$result =
"SELECT UserID, FirstName, LastName," .
" DATE_FORMAT(BirthDate, '%m-%d-%Y') AS BirthDate " .
" FROM Users " .
" WHERE LocationID = 0 " .
" AND UserID ='$id'";
}
echo $result;
e_mysql_result($result); //Bastardized/homegrown PDO
if ($row = mysql_fetch_assoc($result)) {
$retValue['userInfo'] = $row;
...
I'm checking the Notifications table to see if the UserID exists there, if it doesn't it loads what does exist from the Users table, if it does, then it loads everything from the Notifications table.
I'm echoing out the $result and the proper statement is loaded, but it doesn't execute. When I run the concatenated query I get from the PHP preview, it returns just fine.
Before I had to if/else this, I was running the first query, loading everything from the Notifications table, and it was loading just fine. What am I missing?
You can do the whole thing with one query with a LEFT JOIN.
$query= "SELECT U.UserID, U.FirstName,U.LastName, " .
" DATE_FORMAT(U.BirthDate,'%m-%d-%Y') AS BirthDate, " .
" N.Email, N.Phone,N.ProviderName, N.SubNotifications " .
" FROM Users U " .
" LEFT JOIN Notifications N " .
" ON U.UserID = N.UserID " .
" WHERE U.UserID = '$id'";
You are missing execute a query with mysql_query() on all $result
Also change (query variable should be quoted) so change your all variables $id quoted
$result = "SELECT FROM Notifications WHERE UserID=$id";
to
$result = "SELECT FROM Notifications WHERE UserID='$id'";
$r = mysql_query($result);
Note :- mysql_* has been deprecated use mysqli_* or PDO

Does having a mysqli query inside another work?

Here is the answer to moving some data from one table to another it may not be the best, but it does work.
$result = mysqli_query($con,"SELECT * FROM Teacher_staff");
while($row = mysqli_fetch_array($result))
{
// you don't need this step but it checks the select data portion
echo $row['First'] . " " . $row['Last'] . " " . $row['Id'];
// assign your variables, might not need this step as well
$First = $row['First'];
$Last = $row['Last'];
$id = $row['Id'];
// takes the information from the first mysqli and inserts it into the second table.
$sql="INSERT INTO teachers (First, Last, Id)
VALUES
(
'".addslashes($First)."',
'".addslashes($Last)."',
'".addslashes($Depart)."',
'".addslashes($id)."'
)";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
// confirms that each record is added to the table.
echo "1 record added";
}
echo "<br>";
mysqli_close($con);
echo "done";
Any way thanks for the help.... oh and I fixed it so that " ' " doesn't give an error.
Try this query.
$result = mysqli_query($con, "INSERT INTO Teachers (First, Last, Depart) SELECT First, Last, Depart FROM Teacher_staff");
That's literally all you should have to run.
If you have access to your database outside of PHP (phpMyAdmin or command line), I'd recommend running that query from there.

delete a mysql record using multiple selectors

I am trying to delete a record in a MYSQL database when I need to select two simultaneous columns with the WHERE clause:
$result3 = mysqli_query($con, " DELETE FROM Waiting WHERE ToUser='$ToEmail' AND ImageID='$ToEmailDB' ");
if ($result3==false) {
echo "No images waiting for " . $ToEmail . " for image " . $ToEmailDB;
}
else {
echo "Image and record deleted for " . $ToEmail . " for image " . $ToFileName . ".jpg and record " . $GuessImageID;
}
When I execute this statement $result3 returns true but the entry is not deleted. What do I need to change in my formatting? The strings echo back correct data entered in the table.
Shouldn't it be,
"DELETE from Waiting WHERE ToUser = '" . $ToEmail . "' AND ImageID = '" . $ToEmailDB . "'"
$result3 = mysqli_query($con, "DELETE FROM Waiting WHERE ToUser='".$ToEmail."' AND ImageID='".$ToEmailDB."' ");
The query will return true if the SQL query executes successfully, even when the DELETE didn't remove any rows in the DB.
http://php.net/manual/en/mysqli.affected-rows.php
To answer your question, you need to find the number of rows affected
$result3 = mysqli_query($con, " DELETE FROM Waiting WHERE ToUser='$ToEmail' AND ImageID='$ToEmailDB' ");
if (!$result3) {
echo "A database error occurred";
}
else if (mysqli_affected_rows($con) == 0) {
echo "No images waiting for " . $ToEmail . " for image " . $ToEmailDB;
}
else {
echo "Image and record deleted for " . $ToEmail . " for image " . $ToFileName . ".jpg and record " . $GuessImageID;
}
Your query always returns TRUE if its executed successfuly. Only on query failures it returns FALSE As per the PHP documentation:
mysqli_query() Returns FALSE on failure. For successful SELECT, SHOW,
DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object.
For other successful queries mysqli_query() will return TRUE.
From Moby04's Comment
If you want to check if something was actually deleted use mysqli_affected_rows() function.

Using mysql with php and ajax, I want to print out a string (rather than a 0/1) for this query

I apologize if this question has come up before, but I've looked and only found people who are only concerned with the actual result returned by
mysql_query($query);
I'm making a php/mysql page with ajax for a project where the user can create a database and perform a search by interacting with a few select boxes. I would also like to be able to print out the actual query generated by the php, just for testing.
if($dArray[0] == 'sb2a'){
$sql = "SELECT * FROM Vehicles WHERE " . $dArray[1] . " = \'" . $dArray[2] + "\'";}
print($sql);
It just prints 0 rather than something like
"SELECT * FROM Vehicles WHERE VID = '01'"
Any help would be greatly appreciated.
Near the end of your line of code setting the value for $sql:
. $dArray[2] + "\'";
That + should be a .
if($dArray[0] == 'sb2a')
{
$sql = "SELECT * FROM Vehicles WHERE " . $dArray[1] . " = \'" . $dArray[2] . "\'";
}
print($sql);
To concatenation we should always use '.'
Query should be like this.
$sql = "SELECT * FROM Vehicles WHERE {$dArray[1]} = '{$dArray[2]}'";

Categories