Check empty rows query - php

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` != '') ";

Related

PHP Mysqli Delete from DB

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;

how to select with where clause in same table but the string that get pass to table is in a same textbox but has different id

guy's i want to ask about selecting with where clause.
the where clause i use $kode=$_POST['kode_mat'] and i call it in sql query into kode='$kode'.
nah the problem is.. when i have a string that need to pass into the sql query is same, like i use $kode but the $_POST['kode_mat'] has different id like kode_mat1,kode_mat2,kode_mat3,kode_mat4,kode_mat5. and i want to pass it into sql query $sql ="SELECT * FROM material WHERE kode='$kode' ";. how to do it?
i have try to separate the php function into 5 php file. and i think that's make my directory has many file that has been saved. i use this code for the 5 php file
<?php
include("../../Connections/koneksi.php");
$kode=$_POST['kode_mat']; // the variable for pass string i just change $_POST['']; ['kode_mat1'],['kode_mat2'],['kode_mat3']....
// Data for Titik1
$sql ="SELECT * FROM material WHERE kode='$kode' "; // and the query still same just change the id's of the textbox that i need to pass the string
$query = mysqli_query($db,$sql);
$rows = array();
while($tmp= mysqli_fetch_assoc($query)) {
$rows[] = $tmp;
}
echo json_encode($rows);
mysqli_close($db);
?>
this code above has no problem. it show the right value that i need. but i want to try it to make my separate php fuction can be called as one php.
i has to try two code like this but it not work.
1st code i have try
<?php
include("../../Connections/koneksi.php");
$kode=$_POST['kode_mat'];
$kode=$_POST['kode_mat1'];
$kode=$_POST['kode_mat2'];
$kode=$_POST['kode_mat3'];
$kode=$_POST['kode_mat4'];
$kode=$_POST['kode_mat5'];
// Data for Titik1
$sql ="SELECT * FROM material WHERE kode='$kode' ";
$query = mysqli_query($db,$sql);
$rows = array();
while($tmp= mysqli_fetch_assoc($query)) {
$rows[] = $tmp;
}
echo json_encode($rows);
mysqli_close($db);
?>
and the second code i have try
<?php
include("../../Connections/koneksi.php");
$kode=$_POST['kode_mat'];
$kode1=$_POST['kode_mat1'];
$kode2=$_POST['kode_mat2'];
$kode3=$_POST['kode_mat3'];
$kode4=$_POST['kode_mat4'];
$kode5=$_POST['kode_mat5'];
// Data for Titik1
$sql ="SELECT * FROM material WHERE kode='$kode' OR kode='$kode1' OR kode='$kode2' OR kode='$kode3' OR kode='$kode4' OR kode='$kode5'";
$query = mysqli_query($db,$sql);
$rows = array();
while($tmp= mysqli_fetch_assoc($query)) {
$rows[] = $tmp;
}
echo json_encode($rows);
mysqli_close($db);
?>
You can use if and else condition here for your solution like below.
<?php
include("../../Connections/koneksi.php");
if(isset($_POST['kode_mat']) && $_POST['kode_mat'] != "") {
$kode=$_POST['kode_mat'];
} else if(isset($_POST['kode_mat1']) && $_POST['kode_mat] != "") {
$kode=$_POST['kode_mat1'];
} else if(isset($_POST['kode_mat2']) && $_POST['kode_mat2'] != "") {
$kode=$_POST['kode_mat2'];
} else if(isset($_POST['kode_mat3']) && $_POST['kode_mat3'] != "") {
$kode=$_POST['kode_mat3'];
} else if(isset($_POST['kode_mat4']) && $_POST['kode_mat4'] != "") {
$kode4=$_POST['kode_mat4'];
} else {
$kode=$_POST['kode_mat5'];
}
// Data for Titik1
$sql ="SELECT * FROM material WHERE kode='$kode' ";
$query = mysqli_query($db,$sql);
$rows = array();
while($tmp= mysqli_fetch_assoc($query)) {
$rows[] = $tmp;
}
echo json_encode($rows);
mysqli_close($db);
?>

MYSQL Results; no records found statement [duplicate]

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
}
}

MySQL count w/ php trying to optimize for efficiency and non redundancy

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

mysql_query() failing very oddly

This is a really simple thing, but it's not working for some reason. Heres my code.
I am making function (its part of a class) which checks if a username or email exists:
public function exists ($what, $who)
{
$sql = "SELECT * FROM users WHERE $what = $who";
$query = mysql_query($sql);
if (mysql_num_rows($query) != 0)
{
return true;
}
else
{
return false;
}
}
The function returns nothing. In fact if I run that query through regular PHP it returns nothing also. I don't understand why.
This following piece of code returns news entries perfectly:
function fetch($id = '')
{
if (empty($id))
{
$query = 'SELECT * FROM news ORDER BY id desc';
}
elseif (is_numeric($id))
{
$query = "SELECT * FROM news WHERE id = $id";
}
else
{
$route->to(SITE_URL);
}
$result = mysql_query($query);
if (mysql_num_rows($result) > 0)
{
return $result;
}
}
I am confused.
The problem is that you are missing quotes in your query:
$sql = "SELECT * FROM users WHERE $what = $who";
//SELECT * FROM users WHERE username = Mario is not a valid query
should be:
$sql = "SELECT * FROM users WHERE $what = '$who'";
the other queries are working because you are checking against an id, in this case against a string (and in this case you need quotes)
maybe the query execution failed and you have error turned off on screen in your php.ini
Try to add an intermediate check on the correct execution of the query:
$query = mysql_query($sql);
if ($query === FALSE) {
// log error with mysql_errno($conn) and mysql_error($conn);
} else {
if (mysql_num_rows($query) != 0) {
return true;
etc. etc.

Categories