PHP If Else statement not working for database - php

Ok, I'm confused. I have some code that searches a database table for a username, and then uses an if else statement to run some code depending on if the user is found or not. My code is below. The problem is that the code isn't even seeing the if else statement, and I have no idea why. Any help is appreciated.
$sqluser = "select * from users where username='" . $user ."'"; //Searching to see if the user is in the database
echo $sqluser . "<br><br>"; //writes out the select statement to make sure it is correct
$query = mssql_query($sqluser); //returns the results
$num_rows = mssql_num_rows($query); //gets the number of rows returned
echo $num_rows; //writes out the number of rows
if ($num_rows==0) //determines what happens next if the user exists or not
{
//displays an error box if the user doesn't exist
echo "<script type=text/javascript>";
echo "alert('That user doesn't exist. Please try again.')";
echo "</script>";
}
else
{
//will be code to run if the user does exist
echo "<script type=text/javascript>alert('Testing.')</script>";
}

I couldn't add a comment. So I will write this as an answer instead.
Since you state that the alert JavaScript is showing in the page source, this mean that the IF/ELSE statement in PHP is working fine. The problem is with the single quote. You have a single quote inside a single quoted alert function. Hence the JavaScript alert function cannot be executed.
echo "alert('That user doesn't exist. Please try again.')";
Try using this instead
echo "alert('That user doesn\'t exist. Please try again.');";

Related

php sql not deleting row even showing success

I am trying to delete a row using a href, it's not showing the error but it's not delete the row from my table either. Not sure what i'm doing wrong.
delete.php
require_once "db.php";
$id = $_GET['id'];
$sql = "DELETE FROM books WHERE isbn = ". $id;
if (mysqli_query($db, $sql)){
echo "Success";
}else{
echo "Error";
}
main.php
if($resultSet->num_rows > 0){
while($rows = $resultSet->fetch_assoc()){
$au = $rows['author'];
$bt = $rows['booktitle'];
$rev = $rows['reserved'];
echo"<tr><td>$au</td><td>$bt</td><td>$rev</td><td><a href='delete.php?id=".$rows['isbn']."'>Delete</a></td></tr>\n";
}
echo"</table>";
}
I used a back quote (`) around the field name and it is OK now.
Example:
DELETE FROM table WHERE `field_name` = something
It seems like if you're getting the success message then the query ran successfully, which means that the database connection established OK so we can rule that out.
I think that your query is running but not finding any match on the ISBN so the record isn't getting deleted. I would try echoing out the actual SQL query just before execution so you can then copy it, connect to the database and then paste that query in to run yourself. Maybe change it to a SELECT statement first so you can see if it actually gets the row for deletion. If not then a row with that ISBN either doesn't exist or you've got something strange like an extraneous space/other weird character in the ID somewhere.

After login pull data for respective users from db

M building a web app here.The authentication php code looks like this (Please ignore the threats for time being) :
<?php
session_start();
if(isset($_POST['submit']))
{
mysql_connect('localhost','*****','******') or die(mysql_error());
mysql_select_db('cl29-demodb') or die(mysql_error());
$name=$_POST['name'];
$pwd=$_POST['password'];
if($name!='' && $pwd!='')
{
$query=mysql_query("select * from EmployeeTable where EmployeeName ='".$name."' and password='".$pwd."'") or die(mysql_error());
$res=mysql_fetch_row($query);
if($res)
{
$_SESSION['id']=$res['id'];
header('location: profileindex.php');
}
else
{
echo "user name and password are incorrect" ;
echo "<a href=index.php> click here to go back </a>";
}
}
if(!isset($_SESSION['id'])){
echo "Sorry, Please login and use this page";
exit;
}
}
?>
I am able to login successfully and reach the profile of the user.But I want the profile to display only the information for respective users.The profile looks like this:
I have written the php to retrive the name,designation,weekly points,overall points,weekly rank and overall rank respectively.
I tried to echo the variables in the html.
But I am not able to do so.It isnot pulling any data.I have column for all the above fields in the table.
Kindly help.
May be this is the cause
mysql_fetch_row() return the numeric array and you are accessing as $res['id']
either replace mysql_fetch_row with mysql_fetch_array or try numeric index of your id
$_SESSION['id']=$res[0]; or $_SESSION['id']=$res[1];
use mysqli_fetch_assoc so you could call the columns by name if you are using mysql_fetch_array you should call the columns by their index no the by the column name.
There is no need to start a session again in the profileindex.php as the session has already started in the login page.
print the sql and run it in the backend to check if you are getting the desired result in order to further debug this.

mysqli_query(): Empty query in /home/trainman/public_html/Register.php on line 26

I am creating a sign up page.
My code was working perfectly before on an intranet, but now, 5 years later I must use MySQL i.
What happens is I connect to the database using external PHP file, dblogin.php
<?php
$connection = mysqli_connect('mywebhost','username','password','db');
?>
That bit works fine, as the login system works using this.
Then comes my registration system.
It has been a while since I coded in PHP, mostly working using Wordpress now.
<?php
include 'dblogin.php';
if(isset($_GET['i'])){
if($_GET['i'] == '1'){ //if we want to insert a new user
$tblName="tblUsers";
//Form Values into store
$FirstName=$_POST['firstnamecreate'];
$Surname=$_POST['Surnamecreate'];
$Username=$_POST['UsernameCreate'];
$UserType="stu"; //never mind this, it just seperates admins from standard users
$Email=$_POST['EmailCreate'];
$Password=$_POST['PasswordCreate'];
$ExistingUserVerification = mysqli_query ($connection,"SELECT COUNT(*) as num FROM tblUsers WHERE UserName = $Username");
$UserResults = mysqli_query($connection,$ExistingUserVerification);
if($UserResults[0] == 1){
$CreatedStatus = "$Username already exists in the user database. Please choose a different Username.";
}else{
$sql="INSERT INTO $tblName(UserName, Password, UserType, FirstName, Surname, EmailAddress)VALUES('$Username', '$Password', '$UserType', '$FirstName', '$Surname', '$Email')";
$result=mysqli_query($connection,$sql);
if($result){
$CreatedStatus = "$FirstName, you have registered successfully. Click " . "<a href=Login.php>". "HERE". "</a>" . " to login. " . "<br />"."Please note: Hacking of this site is not permitted.";
}
else {
$CreatedStatus = "Unfortunately $Username was not created successfully. Please check your entry or check whether the user already exists.";
}
}
}
}
?>
The problem i am getting is around the
$ExistingUserVerification = mysqli_query ($connection,"SELECT COUNT(*) as num FROM tblUsers WHERE UserName = $Username");
$UserResults = mysqli_query($connection,$ExistingUserVerification);
part.
I have tried all sorts. With the current format, it results in:
Warning: mysqli_query(): Empty query in /home/trainman/public_html/Register.php on line 26
removing $connection results in it expecting 2 parameters and removing i says depricated.
Any help much appriciated. It has been a while since I last used php so sorry if the code is untidy. The select COUNT (*) checks if there is another user with the same username, if there isnt it will submit form values to the DB
This error is coming from the extremely simple fact that you are sending an empty query to mysqli. The query is empty. It's but an empty string. Nothing.
So just check your variables.
The second parameter to mysqli_query() should be a PHP string contains a legitimate SQL query. Anything else will cause an error.

Delete Query returning Value even when there is no record in database

<?php
include "conn.php";
include "session.php";
$name_enterd=$_GET['Name'];
$sql = "DELETE FROM myDB.Mynew WHERE firstname='$name_enterd' OR lastname='$name_enterd'";
echo "<br>";
$result=$conn->query($sql);
if($result==1)
{
echo "<br> Data deleted successfully";
}
else
{
echo "No Data Found<br>";
}
?>
when I run this code 1st time it works properly by deleting the data. But when i run it again it still gives me the same answer" Data Deleted Successfully" even there is no data with that value exists.
i.e $result still gets value1.
Your code should look more like this:
<?php
include "conn.php";
include "session.php";
$name_enterd=$_GET['Name'];
$sql = "DELETE FROM myDB.Mynew WHERE firstname='$name_enterd' OR lastname='$name_enterd'";
echo "<br>";
$result=$conn->query($sql);
if($result->rowCount() > 0)
{
echo "<br> Data deleted successfully";
}
else
{
echo "No Data Found<br>";
}
?>
Specifying rowCount gives you just the number of rows affected by the query
Even when the query only affects 0 rows it has still completed successfully, so you would expect $result to be 1.
You are getting the correct output. When doing that query, you're asking the database to check if there is data with that firstname or lastname and delete it. Even if there is no data with that matches it, the query has still run successfully.
You need to do use
$result->rowCount() == 1
instead of
$result == 1
It really depends what you want to use the result for. If you simply want to tell the user it has been deleted, using what you have is fine. However, if you want to let the user knows if anything has actually been deleted, you need to use my suggestion above or an alternate method to determine if this is the case.
Actually it looks like you might be using mysqli in this code, so maybe you could try using affected_rows instead of rowCount:
see http://php.net/manual/en/mysqli.affected-rows.php.
What does
$result->affected_rows
give you?

MYSQL Tables Picky About Fields?

I am having issues with php and mysql once again. I have a database setup with the table users and I want to make a SELECT COUNT(*) FROM users WHERE {value1} {value2} etc...but the problem is that the 3 fields I want to compare are not in order in the table and when trying the SELECT query, the result vairable($result) is NOT returned properly(!$result). Is there a way to check multiple fields in a mysql table that have fields in between them? Here is an example of what I want to accomplish:
A mysql table called users contains these fields: a,b,c,d,e,f,g,h,i,j,k,l and m.
I want to make a SELECT COUNT(*) FROMusersWHERE a='$_SESSION[user]' and d='$_SESSION[actcode]' and j='$_SESSION[email]' but the statement in quotes is my query and it always executes the if (!$result) { error("An error has occurred in processing your request.");} statement. What am I doing wrong? On the contrary, whenever I try the statement using only one field, ex a, the code works fine! This is an annoying problem that I cannot seem to solve! I have posted the code below, also note that the error function is a custom function I made and is working perfectly normal.
<?php
include "includefunctions.php";
$result = dbConnect("program");
if (!$result){
error("The database is unable to process your request at this time. Please try again later.");
} else {
ob_start();
session_start();
if (empty($_SESSION['user']) or empty($_SESSION['password']) or empty($_SESSION['activationcode']) or empty($_SESSION['email'])){
error("This information is either corrupted or was not submited through the proper protocol. Please check the link and try again!");
} elseif ($_SESSION['password'] != "password"){
error("This information is either corrupted or was not submited through the proper protocol. Please check the link and try again!");
} else {
$sql = "SELECT * FROM `users` WHERE `username`='$_SESSION[user]' and `activationcode`='$_SESSION[activationcode]' and `email`='$_SESSION[email]'";/*DOES NOT MATTER WHAT ORDER THESE ARE IN, IT STILL DOES NOT WORK!*/
$result = mysql_query($sql);
if (!$result) {
error("A database error has occurred in processing your request. Please try again in a few moments.");/*THIS IS THE ERROR THAT WONT GO AWAY!*/
} elseif (mysql_result($result,0,0)==1){/*MUST EQUAL 1 OR ACCOUNT IS INVALID!*/
echo "Acount activated!";
} else {
error("Account not activated.");
}
}
}
ob_end_flush();
session_destroy();
?>
Try enclosing your $_SESSION variables in curly brackets {} and add or die(mysql_error()) to the end of your query -
$sql = "SELECT * FROM `users` WHERE `username`='{$_SESSION['user']}' and `activationcode`='{$_SESSION['activationcode']}' and `email`='{$_SESSION['email']}'";/*DOES NOT MATTER WHAT ORDER THESE ARE IN, IT STILL DOES NOT WORK!*/
$result = mysql_query($sql) or die(mysql_error());
store your session value in another varibles then make query , i think
it's work proper
$usr=$_SESSION['user'];
$acod=$_SESSION['activationcode'];
$eml=$_SESSION['email'];
$sql = "SELECT * FROM `users` WHERE `username`='$usr' and `activationcode`='$acod' and `email`='$eml'";
$result = mysql_query($sql) or die(mysql_error());

Categories