mysql_query with PHP variables - php

This should be easy but I'm can't make it work.
The idea is to look for an email adress posted from a form. If it exists echo something and if not echo something else.
My code is:
<?php
//MySQL Database Connect
mysql_connect("localhost", "********", "**********")
or die("Unable to connect to MySQL");
//get data from form
$email=$_POST['email'];
//ask the database for coincidences
$result = mysql_query("SELECT email FROM pressmails WHERE email='.$email.'");
$num_rows = mysql_num_rows($result);
if($num_rows < 0){
echo "The user is registered";
} else {
echo "The user is not registered";
}
//Close database connection
mysql_close();
?>

You are not concatenating string properly.
$result = mysql_query("SELECT email FROM pressmails WHERE email='.$email.'");
should be
$result = mysql_query("SELECT email FROM pressmails WHERE email='".$email."'");

You should end the string by using a closing quote (if you started the string with " you must end the string with " too, same for ').
And do not forget to use mysql_real_escape_string, otherwise the script is not safe.
The script will become something like this:
// save the query in a variable, so we can echo it to debug when it doesn't work as expected
$sql = "SELECT email FROM pressmails WHERE email='".mysql_real_escape_string($email)."'";
$result = mysql_query($sql);

You do not need the concatenation identifiers, since wrapping a literal in " will automatically parse variables into the string:
$result = mysql_query("SELECT email FROM pressmails WHERE email='$email'");
You should watch out, mind you. Doing the above represents a significant SQL injection vulnerability. You should consider sanitizing $email as a minimum. Also see my comment about the mysql_* functions in PHP.
From the Docs:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_close() PDO: Assign the value of NULL to the PDO object

(assuming you get your syntax errors corrected) isn't the logic of this backwards?
if($num_rows < 0){
echo "The user is registered";
} else {
echo "The user is not registered";
}
if the user is registered their email is in the database and the query returns one or more rows
try
if($num_rows){
echo "The user is registered";
} else {
echo "The user is not registered";
}

Related

How to echo an item from a database

I am still in the process of learning PHP so forgive me for the poor code.
I am attempting to get the users first name to output once they have logged in, however nothing is returning, please may I have some help.
<?php
session_start();
$DATABASE_HOST="localhost";
$DATABASE_USER="root";
$DATABASE_PWORD="";
$DATABASE_NAME="registration";
$connection=mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PWORD, $DATABASE_NAME);
if (mysqli_connect_errno()){
//if there is an issue with connecting to the database, ends code and displays the error
die("failed to connect to server: " .mysqli_connect_error()); //kills program
}
if (!isset($_POST['email'], $_POST['pswd'])){ //checking if both fields were inputted into on the form, isset()checks if data exists
//unable to get data
die("please fill in both email and password"); //kills program
}
$email = mysqli_real_escape_string($connection, $_POST['email']); //saves input as string, preventing misinterpretation
$password = mysqli_real_escape_string($connection, $_POST['pswd']);//saves input as string, preventing misinterpretation
$SQLstatement = "SELECT * FROM users WHERE email='$email' and password='$password'"; //querys the database for match
$Queryresult = mysqli_query($connection, $SQLstatement) or die(mysqli_error($connection)); //runs the query
$rowsQueryResult = mysqli_num_rows($Queryresult);//number of 'emails' in database where the emails match
$dbFirstName=$rowsQueryResult ['firstName'];
if ($rowsQueryResult==1){//if the number of emails where a match is made, is 1
echo "Welcome $dbFirstName <br/> ";
echo "successful login. <a href='accountPage.php'>Click</a> here to access the accounts page"; //successful login, links to accounts page
$_SESSION['firstName']=$dbFirstName;
}else{ //if matches are 0 or >=2
die ('unsuccessful login'); //kills program
}
?>
Thank you for your time and help
This problem can be solved by using the mysqli_fetch_assoc() function in place of mysqli_num_rows(). However, I would recommend you to use PDO since it's easier to implement and more readable.
The mysqli_num_rows() function returns the number of rows in a result set.
$rowsQueryResult = mysqli_num_rows($Queryresult);`
will give number of 'emails' in database where the emails match.
You need to use mysqli_fetch_assoc() as
$row = mysqli_fetch_assoc($Queryresult);
$dbFirstName=$row['firstName'];

mysql_query() Is Returning Error "No Database Selected"?

I'm writing a script that let's users update their passwords. It does this by first locating the entered email address of the user, then updates the password to whatever they create. However, I'm getting a "no database selected" error from mysql_query(). The email address I'm testing is valid and is in the database, and my query syntax looks good. I don't know what could be causing this. Any advice would be appreciated, thank you all in advance.
Furthermore, my form that is posting these values is ok, as I've looked over that many times.
<?php
mysql_connect('localhost','calsheet_project','UUx[#]MoF4?F') or die("couldn't connect!");
$eml = $_POST['data'];
$newPassword = $_POST['data1'];
$cnewPassword = $_POST['data2'];
$query = mysql_query("SELECT * FROM accounts WHERE email = $eml") or die(mysql_error());
$fetch = mysql_fetch_array($query);
var_dump($fetch);
echo mysql_error();
if($fetch > 0) {
mysql_query("UPDATE accounts SET password=$cnewPassword WHERE
email=$eml");
echo "Password Reset!";
} else {
echo "email address cannot be found.";
};
?>
If working correctly, it should update the password field for the associated email address of the user. But, it's showing the error "no database selected."
You should use the following code before you executemysql_query
// select the query database
mysql_select_db("db_name");
and the PHP official said mysql_connect() is not good anymore for security reasons.
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, > the MySQLi or PDO_MySQL extension should be used.
for more details see http://php.net/manual/en/function.mysql-connect.php

mysql Duplicate error handling

I'm trying to use PHP to enter data from a form. When I try to enter duplicate data a bad message pops like
Something went wrong with this:
INSERT INTO customer VALUES('jamie9422','Jamie Lannister','sept of baelor','jamie#cersei.com',9422222222,0) Duplicate entry 'jamie9422' for key 'PRIMARY' "
Instead, I want to display a clean error message. How can I do that. Here's my code I've written so far...
<?php
include_once "dbConnect.php";
$connection=connectDB();
if(!$connection)
{
die("Couldn't connect to the database");
}
$tempEmail = strpos("{$_POST["email"]}","#");
$customer_id=substr("{$_POST["email"]}",0,$tempEmail).substr("{$_POST["phone"]}",0,4);
//$result=mysqli_query($connection,"select customer_id from customer where customer_id='$customer_id' ");
//echo "customer_id is".$result;
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";
$customer_idcip = $customer_id-1;
echo $customer_idcip;
if ( mysql_query($query)) {
echo "It seems that user is already registered";
} else {
$command = "INSERT INTO customer VALUES('{$customer_id}','{$_POST["name"]}','{$_POST["address"]}','{$_POST["email"]}',{$_POST["phone"]},0)";
$res =$connection->query($command);
if(!$res){
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
echo "Welcome ".$_POST["name"]." \nCongratulations on successful Registration. Refill your Wallet here";
//$cutomerRetrival = mysql_query("select from customer where customer_id='$customer_id'");
echo "<br>Please note your customer ID :".$customer_id;
}
/*if($result)
{
echo "Query Fired";
$dupentry = mysqli_num_rows($result);
if($dupentry==1)
{
echo "You are already Registered";
exit;
}
}*/
?>
The error code (number) is 1022.
You can e.g. define a constant for that (so that somebody else in x months has a chance to understand the code) like
define('ER_DUP_KEY', 1022);
and then do something like
if(!$res){
if ( <error code>==ER_DUP_KEY ) {
handleDuplicateEntryError();
}
else {
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
}
since I don't know how $res =$connection->query($command); works (and what $connection is I can't tell you exactly how to implement <error code>==ER_DUP_KEY, could be by using mysql_errno.
But it seems to be somehow intermingled with mysql_query($query), i.e. the old, deprecated mysql_* extension and some custom class. You might want to fix that first.... ;-)
see http://docs.php.net/manual/en/mysqlinfo.api.choosing.php
Your code doesn't check for existing record properly
Change
if (mysql_query($query)) {
echo "It seems that user is already registered";
}
to
$result = mysql_query($query);
if (mysql_num_rows($result)) {
echo "It seems that user is already registered";
}
Also, PLEASE do not use $_POST variables without escaping them first, use something like mysql_real_escape_string() to escape each variable passed from the user, otherwise your website will be hacked really fast with SQL Injection.
Make some update into your and then try to get error message 'customer already registered.'
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";
$res= mysql_query($query);
$customer_count = mysql_num_rows($res);
$customer_idcip = $customer_id-1;
echo $customer_idcip;
if ( $customer_count > 0 ) {
echo "It seems that user is already registered";
} else {
...................................
Thank you all.
Actually I was using mysqli API in my connectDB.php file..
Hence I needed to call functions on mysqli.
Instead I was calling mysql. i.e I was creating a new connection, thus the query wasn't getting fired at all.
Changed to mysqli->query($result) that is object oriented style
and it worked fine....
Use Try Catch instead.
try{
$res =$connection->query($command);
}catch(Exception $e){
die( "Write your error appropriate message here");
}

login function is not working properly

Hello I facing a strange problem; I am using this code to check the login data with my db
include("includes/config.php");
include("includes/database.php");
$name = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM info_user WHERE user_name = '$name' AND password = '$pass'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['user_name']. " - ". $row['password'];
if (mysql_num_rows($sql)) {
echo "success";
}
else
{
echo "failed";
}
here, when i succeed it shows success but any blank input or wrong input is not showing the failed message why? and how can I solve it? is there any better way to check the login? please help
Thanks in advance
First off:
$row = mysql_fetch_array($result) or die(mysql_error());
If you pass along a wrong username or password, mysql_fetch_array() will return FALSE, because there is no rows to take from. This results in your or die(mysql_error()) part being executed, which means your script dies and outputs nothing since mysql didn't fail - which again means that mysql_error() has nothing to return to you.
Secondly, you are using mysql_num_rows() on the $sql string, not on the $result variable which actually contains a mysql resource that you should be using.
You should also check the mysql_num_rows() before using mysql_fetch_array() so that you don't try to pull out some data you don't have available.
Lastly, your solution is full of security flaws. You are passing along raw post data to your mysql database which makes you vulnerable to sql injection and you are storing your passwords as plain text values in your database (not plain text files, just plain text values).
You should google sql injection and password hashing to improve your security.
Try this:
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
echo "success";
} else {
echo "failed";
}

Simple PHP Login - num_rows

I am using mysql_num_rows to check if one row is returned for my user login and if count == 1 then log user in, I get an error though below my code is after that. Any suggestions?
Warning: mysql_num_rows(): supplied
argument is not a valid MySQL result
resource in
/home/web42001spring09/rcoughlin/public_html/process-login.php
on line 13
<?php
// include database info
include("config.php");
if(isset($_POST["submit"])){
// get data from form
$username = $_POST["user"];
$password = $_POST["pass"];
$query = "SELECT username,password,id FROM login WHERE username=".$username." AND password=".$password." LIMIT 1";
$result = mysql_query($query);
$count = mysql_num_rows($result);
// if 1 then login them in set cookie and redirect
if($count==1){
setcookie("password", "".$password."", time()+3600);
setcookie("username", "".$username."", time()+3600);
header("Location:admin.php");
}else{
echo "Wrong Username or password combination";
}
}else{
echo "Must be submitted via form.";
}
Not sure why the code is drawing that issue? I have used this method before.
You're not quoting your strings in the query, so your SQL statement is invalid.
$query = "SELECT username,password,id FROM login WHERE username='" . mysql_escape_string($username) . "' AND password = '" . mysql_escape_string($password) . "' LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
You need to add quotes AND use mysql_escape_string or mysql_real_escape_string to prevent SQL injection attacks.
Firstly, check for errors...
The "supplied argument is not a valid MySQL result resource" because there was an error in your SQL, but you haven't made life easy for yourself by ignoring the failed query. Use mysql_error to get the error message.
Secondly, properly escape strings in SQL...
Once you see the error, you'll see you missed some quotes in your query, but you must also escape the strings you put in a query, otherwise you're vulnerable to SQL injection attacks...
$query = "SELECT username,password,id FROM login ".
"WHERE username='".mysql_real_escape_string($username)."' ".
"AND password='".mysql_real_escape_string($password)."' LIMIT 1";
$result = mysql_query($query);
if ($result)
{
$count = mysql_num_rows($result);
// if 1 then login them in set cookie and redirect
if($count==1){
setcookie("password", "".$password."", time()+3600);
setcookie("username", "".$username."", time()+3600);
header("Location:admin.php");
}else{
echo "Wrong Username or password combination";
}
}
else
{
echo "Error:".mysql_error()."<br>;
}
Always use mysql_real_escape_string when building a query, or use a wrapper class library which does it for you with parameterised queries, like PDO or ADODb
Finally, a word on those cookies...
Also, logging someone in by giving them a cookie with the username and password isn't a terribly good way to implement a login. Aside from transmitting the password in the clear with every request, it's highly vulnerable to a cookie theft attempt. Given your naive approach to SQL security, it's likely you'll also be leaving yourself vulnerable to XSS attacks making it easy for someone to collect those cookies :)
Looks like you might want to do 2 things:
Sanitise your input - passing user-submitted data straight into a database query is a recipe for disaster (see mysql_real_escape_string(string $unescaped_string)).
Put quotes around literals in database queries (i.e. username ='".$username."')
The error message you're getting is due to the fact that the MySQL result object ($result) is not valid. Try calling mysql_error() to see what error message MySQL returns.
Try:
$row = mysql_fetch_row($result);
if ($row) { // success
Assuming you'd probably want to fetch some columns along with the authentication check (e.g. real name, last login etc.)
Do never store user authentication data in a cookie!
Because both password and login are strings, you need to change the SQL:
$query="SELECT username,password,id FROM login WHERE username='".$username."' AND password='".$password."' LIMIT 1"
The query is invalid (the $result == false)
Line:
$query = "SELECT username,password,id FROM login WHERE username=".$username." AND password=".$password." LIMIT 1";
Should be replaced by:
$query = "SELECT username,password,id FROM login WHERE username='".mysql_escape_string($username)."' AND password='".mysql_escape_string$password)."' LIMIT 1";
The PHP mysql_query() function doesn't give errors by default.
Using a function that shows sql errors allow you to spot these errors easily.
function my_query($sql) {
$result = mysql_query($sql);
if ($result === false) {
trigger_error('['.mysql_errno().'] '.mysql_error(), E_USER_WARNING);
}
return $result;
}
Right now the username and password are injected directly in the sql string.
What you want is password = "secret", now the query contains password = secret
Mysql error "unknown column sercet"
PS:
Using a "LIMIT 1" here is a sign that there are several users (ids) using the same username password combination. (Not recommended)

Categories