PHP Check mysqli_num_rows not working - php

I've searched thoroughly and nothing seems to be working; I have this code here which posts into my database but the problem is I am trying to run a conditional which checks if a row exists using the mysqli_num_rows function, but it is not actually working. I have tried many different versions and other functions as well such as mysqli_fetch_row, but nothing seems to work. Here is my code:
if (!empty($_POST)) {
$db_conx="";
$name = $_POST['name'];
$module = $_POST['module'];
$secret = $_POST['secret'];
$uid1 = $dmt->user['uid'];
$queryA = "INSERT INTO table_a (uid1,name,module,secret) VALUES ('$uid1','$name','$module','$secret')";
$resultA = mysqli_query($db_conx,$queryA);
$queryB = "SELECT 1 FROM table_a WHERE name='$name' LIMIT 1";
$resultB = mysqli_query($db_conx,$queryB);
$resultC = mysqli_query($db_conx,$queryB);
$query = mysqli_query($db_conx,"SELECT * FROM table_a WHERE name='$name'");
if (empty($name)||empty($module)||empty($secret)) {
echo "Oops! Can't leave any field blank <br />";
exit();
} elseif(mysqli_num_rows($query) > 0){
echo "name already exists.";
exit();
} elseif ($db_conx->query($queryA) === TRUE) {
echo "New record created successfully.";
exit();
} else {
echo "Error: " . $queryA . "<br>" . $db_conx->error;
exit();
}
}
As you can see the query appears to run but indeed does not do what it's told.

The first line of code inside your IF is destroying the variable you are using to hold the database connection
if (!empty($_POST)) {
$db_conx=""; // get rid of this line
So basically nothing using the mysqli API will work.
ALSO:
Add these as the first 2 lines of a script you are trying to debug
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
as you are obviously not readng your php error log

Related

I am trying to run my website on an online host but i keep getting an error

Every time i am trying to run the following PHP code on 000Webhost, i keep getting this error
-- mysqli_num_rows() expects parameter 1 to be mysqli_result.
The same code had been run successfully without errors on my localhost, XAMPP, i have looked through many examples and only found out that this error is caused by an error in the query, but as mentioned, the query works perfectly on my localhost.
The error is indicated in the code.
Any help would be appreciated.
<?php
session_start();
//decalre variables
$DeviceID ="";
$productID ="";
//connect to database
$db = mysqli_connect('localhost','id5655845_grocerywatch1234','123456','id5655845_grocerywatch1234');
//validate product id and device id are avaliable
if(isset($_POST['validate_user'])){
$DeviceID = mysqli_real_escape_string($db,$_POST['DeviceID']);
$productID = mysqli_real_escape_string($db,$_POST['productID']);
$query = "SELECT * FROM configuration WHERE DeviceID='$DeviceID' AND productID='$productID'";
$result1 = mysqli_query($db,$query);
echo $query;
//error indicated on the following line.
if(mysqli_num_rows($result1) == 1){
$_SESSION['DeviceID'] = $DeviceID;
$_SESSION['success'] = "You are now logged in";
header('location: register.php');
}
else{
echo "Device Not registered";
echo "Product Doesnt Exist";
}
}
I think your query is likely failing. The return value for mysqli_query is False on failure, otherwise it is mysqli_result. See docs here
Fix by properly formatting string:
...
$query = "SELECT * FROM configuration WHERE DeviceID='".$DeviceID."' AND productID='".$productID."'";
$result1 = mysqli_query($db,$query);
echo $query;
if ($result1 == false){
echo "Error has occurred!";
}
elseif (mysqli_num_rows($result1) == 1){
$_SESSION['DeviceID'] = $DeviceID;
$_SESSION['success'] = "You are now logged in";
header('Location: register.php');
}
else{
echo "Device Not registered";
echo "Product Doesnt Exist";
}
The query either returned no rows or is erroneus, thus FALSE is returned. Change it to
if (!$dbc || mysqli_num_rows($dbc) == 0)
Return Values
Returns TRUE on success or FALSE on failure. For SELECT, SHOW,
DESCRIBE or EXPLAIN mysqli_query() will return a result object.

Writing a blog forum... and need help on sql

This sql function works on all my scripts except this one. Does anyone see what's wrong with it? The part that isn't working... is the part where it's supposed to insert the variable into a table. The include is for logging in the database, and that's all correct(I double checked).
<?php
session_start();
include_once 'dbh.php';
$confirm = $_POST['confirm'];
$check = $_SESSION['forum_name'];
if ($confirm == $check) {
include_once 'dbh.php';
$sql = "INSERT INTO forum_names (name) VALUES ('$forum_name');";
$result = mysqli_query($conn, $sql);
header("Location: ../redir.php?postsuccess=success");
} else {
echo "Your names do not match" . " ";
echo "<a href='../redir.php'>Click here to try again</a>";
}
?>
$forum_name doesn't exist. Therefore, either replace it with $check, or replace $check with $forum_name.
I have zero idea how this could possibly work on other pages using that code.

Mysql_num_rows not returning any value

What is the problem in my code ? every time it echo This image used as cover image , but delete query work properly.how can i fix it?
<?php
session_start();
if(!empty($_SESSION['userId']) && !empty($_SESSION['name'])){
include ('connect.php');
dbConnect();
if (isset($_GET['ximgid'])) {
$del=mysql_query("Delete FROM project_image WHERE ximgid='".$_GET['ximgid']."' And coverflag !='1'");
$delete=mysql_num_rows($del);
if($delete==1){
echo "<script type='text/javascript'>alert('Sucessfully Delete !!!')</script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}else{
echo "<script type='text/javascript'>alert('This Image Used As Cover Image')</script>";
echo "<script >window.location.href = 'projectImage.php'</script>";
}
}else{
echo "<script>javascript:window.location = 'index.php'</script>";
}
}
?>
mysql_num_rowsonly works with selectstatement.
For delete statements you have to use mysql_affected_rows
Here the part of the documentation of mysql_affected_rows:
Retrieves the number of rows from a result set. This command is only
valid for statements like SELECT or SHOW that return an actual result
set. To retrieve the number of rows affected by a INSERT, UPDATE,
REPLACE or DELETE query, use mysql_affected_rows().
mysql_affected_rows() is the way to go
$delete=mysql_affected_rows($del);
if($delete>0){
echo "<script type='text/javascript'>alert('Sucessfully Delete !!!') </script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}else if($delete==0){
echo "<script type='text/javascript'>alert('This Image Used As Cover Image')</script>";
echo "<script >window.location.href = 'projectImage.php'</script>";
}else{
echo "<script type='text/javascript'>alert('mysql error')</script>";
}
I had to solve my problem in an alternative way which is given below:
<?php
session_start();
if(!empty($_SESSION['userId']) && !empty($_SESSION['name'])){
include ('connect.php');
dbConnect();
if(isset($_GET['ximgid'])){
$selQuery = "SELECT coverflag FROM project_image WHERE ximgid ='".trim($_GET['ximgid'])."' AND zid = '1000' AND xpid = '".trim($_GET['pid'])."'";
$flagtResult=mysql_query($selQuery);
$flagRow=mysql_fetch_array($flagtResult);
mysql_free_result($flagRow);
$cover=$flagRow[0];
if($cover == 1){
echo "<script type='text/javascript'>alert('Used as cover picture')</script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}else{
$sql = "DELETE FROM project_image WHERE ximgid = '".trim($_GET['ximgid'])."' AND coverflag != '1' AND zid = '1000' AND xpid = '".trim($_GET['pid'])."'";
$result = mysql_query($sql) or die(mysql_error());
if($result > 0){
echo "<script type='text/javascript'>alert('Sucessfully Detele !!!')</script>";
echo "<script>javascript:window.location = 'projectImage.php'</script>";
}
}
}
}else{
echo "<script>javascript:window.location = 'index.php'</script>";
}
?>
Now I can get my proper output.. Thanks Everyone.
first of all it appears that you are escaping ximgid and coverflag with ' which would throw a syntax error in your sql if those were not varchar fields.
$del=mysql_query("Delete FROM project_image WHERE ximgid=".$_GET['ximgid']." And coverflag !=1;");
Second issue to address would be that you are taking a $_GET parameter and putting it directly into your SQL query which is just trouble looking to happen so I would suggest next changing it to:
$del=mysql_query("Delete FROM project_image WHERE ximgid=".mysql_real_escape_string($_GET['ximgid'])." And coverflag !=1;");
if you need extra help debugging your SQL you can always temporarily put a call to
echo mysql_error();
after your call to mysql_query in order to show the error message from the server.

PHP copy and unlink being ignored

This code runs when a user hits a delete button on my form. I am trying to copy a file, $picfile, from "/pics/" to "/pics/deletedrecordpics/" and then delete the orginal. Finally, delete the record from the database. Deleting the record from the databse works, but copying the file and deleting the original does nothing. There are no errors in the error log, so I am really confused as to why this code isn't running as I think it should.
if ($allowdelete==true && $thepassword == $password)
{
//delete record that delete was set to by button
//$sql = ("DELETE FROM $table WHERE id=$id");
$sql = ("select picfile,title,author from $table where id=$delete");
$file=mysql_query($sql);
$resrow = mysql_fetch_row($file);
$picfile = $resrow[0];
$title = $resrow[1];
$author = $resrow[2];
if (file_exists("/pics".$picfile)){
copy("/pics/".$picfile,"/pics/deletedrecordpics/".$author."-".$title."-".$picfile);
unlink("/pics/".$picfile);
echo $available = "image is available.";
$sql = ("DELETE FROM $table WHERE id=$delete");
$result = mysql_query($sql);
if ($result){
echo "Your Picture has been removed from our system.";
Die($available);
}
else{
echo "There was an error in removing your picture.";
$Delete = "";
Die();
}
}
else{
echo $available = "image is not available.";
}
}
The weird part is a have almost the same code in a delete button on my control panel located in "/adminpanel" and it works perfectly. The code for that is the same except I use $id instead $delete and "../" before all the "pics/" because it's in the adminpanel folder. The permissions are right and the folder exists because the code works with that page. And I know $delete is getting set because the record gets deleted from the database. I know picfile, author and title are getting set because I appended them to the print statement and they were all right. Really confused. Any ideas?
Here is the code for the working page
q = ("select picfile,title,author from $table where id=$id");
$file=mysql_query($q);
$resrow = mysql_fetch_row($file);
$picfile = $resrow[0];
$title = $resrow[1];
$author = $resrow[2];
copy("../pics/".$picfile,"../pics/deletedrecordpics/".$author." - ".$title." - ".$picfile);
unlink("../pics/".$picfile);
$file=mysql_query($q);
$q = ("DELETE FROM $table WHERE id=$id");
$file=mysql_query($q);
why is this line repeated twice $file=mysql_query($q); ?
Try this
$file_path = $_SERVER["DOCUMENT_ROOT"]."/pics/";
if (file_exists($file_path.$picfile))
{
copy($file_path.$picfile, $file_path."/deletedrecordpics/".$author."-".$title."-".$picfile);
unlink($file_path.$picfile);
}
else
{
echo "File not found!!!!!!!!";
}

Cant track error cause in PHP page updating a MS SQL database

Simple PHP page (I'm no PHP expert, just learning) to update a MS SQL database. The following code generates an error that I dont know how to solve.
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE USERID='".$_REQUEST['user_id']."';";
if ($result = odbc_exec($dbconnect, $query)) {
echo "// Success!";
}
else {
echo "// Failure!";
}
odbc_close($dbconnect);
//End Update
This fails every time in the "if ($result ..." section
However, if I run virtually the same code
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '89990.jpg' WHERE USERID='80'";
if ($result = odbc_exec($dbconnect, $query)) {
// Success!
}
else {
// Failure!
}
odbc_close($dbconnect);
//End Update
It works just fine. I have echoed the $query string to the screen and the string is the same for both. I can't figure out why it fails in one and not the other?
Also weird is when I use a parameterized query such as
include '/connections/SFU.php';
$query = "UPDATE dbo.Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = $_REQUEST['user_id'];
$fn = $file["name"];
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
The query fails in the prepare section above, but fails in the odbc_exec section below:
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = "80";
$fn = "samplefile.jpg";
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
In all cases I do not get any odbc_errormsg ().
Remove the extra ; from your query.
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id']."';";
^
So your query should be,
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id'];
Also have practice of using odbc_errormsg() so you can have a better idea why your query gets failed.
Warning: Your code is vulnerable to sql injection attacks!

Categories