This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Display Data From MYSQL; SQL statement error
I have the code below displaying data from a MYSQL database (currently looking into sql injection issue) I need to insert an error message when no results are found...not sure where to position this! I have tried the code if( mysql_num_rows($result) == 0) {
echo "No row found!" but keep on gettin syntax errors, does anyone know the correct position in the code for this?
--
require 'defaults.php';
require 'database.php';
/* get properties from database */
$property = $_GET['bedrooms'] ;
$sleeps_min = $_GET['sleeps_min'] ;
$availability = $_GET['availability'] ;
$query = "SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' AND sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'";
$row=mysql_query($query);
$result = do_query("SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'", $db_connection);
while ($row = mysql_fetch_assoc($result))
{
$r[] = $row;
}
?>
I have found few errors in your code that in line
$query = "SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' AND sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'";
$row=mysql_query($query);
You use bedrooms = '{$bedrooms}' but $bedrooms is not variable in whole cod it must be $preopery. I have made a few changes in your code given below please try it.
<?php
require 'defaults.php';
require 'database.php';
/* get properties from database */
/*if get $_GET['bedrooms'] value else ''*/
if (isset($_GET['bedrooms'])) {
$property = $_GET['bedrooms'];
} else {
$property = '';
}
/*if get $_GET['sleeps_min'] value else ''*/
if (isset($_GET['sleeps_min'])) {
$sleeps_min = $_GET['sleeps_min'];
} else {
$sleeps_min = '';
}
/*if get $_GET['availability'] value else ''*/
if (isset($_GET['availability'])) {
$availability = $_GET['availability'];
} else {
$availability = '';
}
$query = "SELECT * FROM `properties` WHERE bedrooms = '" . $property . "' AND sleeps_min = '" . $sleeps_min . "' AND availability = '" . $availability . "'";
$result = mysql_query($query) or die(mysql_error());
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$r[] = $row;
}
}
?>
Do var_dump($GET_) to debug whether you are getting valid strings. If any of these are blank, the query will try to match blank values instead of NULL. You should prevent this by doing:
if(!$_GET['bedrooms'] || $_GET['bedrooms'] == ''){
$property = 'NULL';
}//repeat for all three
$query = "SELECT * FROM `properties` WHERE 'bedrooms' = '$bedrooms' AND 'sleeps_min' = '$sleeps_min' AND 'availability' = '$availability'";
Instead of:
while ($row = mysql_fetch_assoc($result)) {
$r[] = $row;
}
You can simply do:
$r = mysql_fetch_array($query);
But enclose that in a conditional to see if your query found anything:
if(mysql_affected_rows() > 0){
//your code here will execute when there is at least one result
$r = mysql_fetch_array($query);
}
else{//There was either nothing or an error
if(mysql_affected_rows() == 0){
//There were 0 results
}
if(mysql_affected_rows() == -1) {
//This executes when there is an error
print mysql_error(); //not recommended except to debug
}
}
Related
So I thought this would be a simple query to just delete rows that didn't have any data stored under certain columns, but for some reason my query is returning that zero rows have been deleted, I checked the table and they are still there.
What I want to do is delete from my gps_routes table where the route_lat and route_long do not contain a location (empty).
I have checked my to make sure I have delete permissions enabled as well.
$sql = "SELECT * FROM gps_routes";
$result = $link->query($sql);
$rowCount = $result->num_rows; $rows_deleted = 0; $delete_row = false;
if ($rowCount > 0)
{
while($row = $result->fetch_assoc())
{
$user = $row['user_email'];
$id = $row['route_id'];
$lat = $row['route_lat'];
$lng = $row['route_long'];
if (empty($lat) || empty($lng)){
$delete_row = true;
}
if (ctype_space($lat) || strlen(trim($lat)) == 0){
$delete_row = true;
}
if ($lat == '' || $lat == ""){
$delete_row = true;
}
if ($delete_row){
$rows_deleted++;
mysqli_query($link, "DELETE FROM gps_routes WHERE user_email = '$user' AND route_id = '$id'");
}
}
echo "Routes deleted: $rows_deleted";
}
From your code is suggest that you just want to go through your DB and check to see if the lat and long are empty. If they are then delete them.
Sounds like you can just use this query to get the job done.
mysqli_query($link, "DELETE FROM gps_routes WHERE (route_lat = '' OR route_lat IS NULL) OR (route_long = '' OR route_long IS NULL)");
This is how I would do it based off the code you have provided:
$query = "DELETE FROM gps_routes WHERE (route_lat = '' OR route_lat IS NULL) OR (route_long = '' OR route_long IS NULL)";
$result = $link->query($query);
echo 'Routes deleted: ' . $result->num_rows;
I am trying to only allow a submission via the form only if a party_id exists in a table using empty, here is my code at the moment it is still allowing everything through even if there is no party_id.
Any help would be great.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='" . $party_id . "'";
$res = mysqli_query($link, $sql);
if(empty($party_id)) { #Were any records found?
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");
A simpler way might be to just check if the query returned any results like this.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='$party_id'";
$res = mysqli_query($link, $sql);
if ( mysqli_num_rows($res ) == 0 ) {
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");
In fact I am working on a small PHP script but I am facing a problem right now.The problem is that i want to check if my query return records this is my mysqli query:
$sql = "select * from specs where btitleid=$id and phoneid=$aydi"
$check = $conn->query($sql)
while($row = $check->fetch_assoc()) {$tocheck = $row['content'];}
I don't want to check the number of rows of this query to see if it is null.I want to check if all $row['content'] are empty.
How about this:
$sql = "select * from specs where btitleid=$id and phoneid=$aydi";
$check = $conn->query($sql);
$contentAllEmpty = true;
while ($row = $check->fetch_assoc()) {
if (strlen($row['content']) > 0) {
$contentAllEmpty = false;
}
}
if ($contentAllEmpty) {
//do something
}
use ==
while ($row = $check->fetch_assoc()) {
if ($row['content'] == '') {
... code here
}
}
To get back only records where the content column is not empty -
$sql = "SELECT * FROM `specs` WHERE `btitleid` = $id AND `phoneid` = $aydi AND (`content` IS NOT NULL OR `content` != '') ";
My query is working OK. But I am trying to find out the best way to optimize and not have to repeat my $sqlRecCount and $records_count (and would like to know if it's possible to not need to duplicate the GETs). This is what I have now:
if ((int)$_GET['products_id'] === 13) {
$sqlRecCount = "select count(*) as recTotal from table_sql_1";
$recCnt = $db->Execute($sqlRecCount);
$records_count = $recCnt->fields['recTotal'];
}
elseif ((int)$_GET['products_id'] === 2) {
$sqlRecCount = "select count(*) as recTotal from table_sql_2";
$recCnt = $db->Execute($sqlRecCount);
$records_count = $recCnt->fields['recTotal'];
} else {
$records_count = "Updating...";
}
$id = intval($_GET['products_id']);
if ($id == 13 || $id == 2) {
$sqlRecCount = "select count(*) as recTotal from table_sql_" .
($id==13?'1':'2');
$recCnt = $db->Execute($sqlRecCount);
$records_count = $recCnt->fields['recTotal'];
} else {
$records_count = "Updating...";
}
ps: if you have a set of tables without direct correspondence to the product_id you can rewrite snippet as
$id = intval($_GET['products_id']); // casting to int is not required here
$tables = array('13'=>'1', '2'=>'2', and so on);
if (isset($tables[$id])) {
$sqlRecCount = "select count(*) as recTotal from table_sql_" . $tables[$id];
$recCnt = $db->Execute($sqlRecCount);
$records_count = $recCnt->fields['recTotal'];
} else {
$records_count = "Updating...";
}
ps: #downvoter - any comment?
The right way apparently would be
if ($id = (int)$_GET['products_id']) {
$sql = "SELECT count(*) as total FROM table_sql WHERE products_id=$id";
$res = $db->Execute($sql);
$records_count = $res->fields['total'];
}
or something similar according to your db API syntax
I have PHP function which checks to see if variables are set and then adds them onto my SQL query. However I am don't seem to be getting any results back?
$where_array = array();
if (array_key_exists("location", $_GET)) {
$location = addslashes($_GET['location']);
$where_array[] = "`mainID` = '".$location."'";
}
if (array_key_exists("gender", $_GET)) {
$gender = addslashes($_GET["gender"]);
$where_array[] = "`gender` = '".$gender."'";
}
if (array_key_exists("hair", $_GET)) {
$hair = addslashes($_GET["hair"]);
$where_array[] = "`hair` = '".$hair."'";
}
if (array_key_exists("area", $_GET)) {
$area = addslashes($_GET["area"]);
$where_array[] = "`locationID` = '".$area."'";
}
$where_expr = '';
if ($where_array) {
$where_expr = "WHERE " . implode(" AND ", $where_array);
}
$sql = "SELECT `postID` FROM `posts` ". $where_expr;
$dbi = new db();
$result = $dbi->query($sql);
$r = mysql_fetch_row($result);
I'm trying to call the data after in a list like so:
$dbi = new db();
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql .= " ORDER BY `time` DESC LIMIT $offset, $rowsperpage";
$result = $dbi->query($sql);
// while there are rows to be fetched...
while ($row = mysql_fetch_object($result)){
// echo data
echo $row['text'];
} // end while
Anyone got any ideas why I am not retrieving any data?
while ($row = mysql_fetch_object($result)){
// echo data
echo $row->text;
} // end while
I forgot it wasn't coming from an array!