mysql php query dies - php

Im creating a login php script that connects to a mysql db with a table called users containing a list of users. I am running into what looks like either an empty set or a mysql error.
I have included a connection error echo and a query die echo and the script is echoing the latter error that gives me the query string. I run this exact query in phpMyAdmin and get the result I expect (it returns the user).
Why is it dying?
$cxn was defined on the login page that calls this posts to this page
$pass = addslashes($_POST['password']);
$email = addslashes($_POST['username']);
$pw = md5($_POST['password']);
$query = "SELECT * FROM `users` WHERE (`user_email`='$email' AND `user_pass`='$pw')" ;
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($cxn,$query) or die(mysqli_error($cxn)."Query= ".$query);
Ive left the first version up. Here is the current incarnation which has the same result.
<?php
$email = ($_POST['username']);
$pw = md5($_POST['password']);
$query = "SELECT * FROM `users` WHERE (`user_email`='$email' AND `user_pass`='$pw')" ;
if (mysqli_connect_errno($cxn)){ //remove later
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} //to here
$result = mysqli_query($cxn,$query) or die(mysqli_error($cxn)."Query=".$query);
echo '<hr>';
echo $result;
while($row = mysql_fetch_array($result)){
echo $row['user_email'];
echo '<hr>';
echo $row['user_pass'];
echo '<hr>';
echo $row['user_fname'];
echo '<hr>';
}
?>

Because your not passing $cxn variable while checking connection:
Change this:
if (mysqli_connect_errno()){
to:
if (mysqli_connect_errno($cxn)){

I just noticed this but you have the following:
$email = ($_POST['username']);
And this should be simply:
$email = $_POST['username'];
Also, try writing your query like this:
$query = "SELECT * FROM `users` WHERE `user_email` = '".$email."' AND `user_pass` = '".$pw."'";

Related

can't retrieve data from database phpMyAdmin

I'm a beginner in learning how to set up database & PHP script and follow example
to do that, then when I run login.php script I can't retrieve data from the database ,
I really feel that is a very simple question for others but I tried to solve it But didn't succeed, so can someone take look on my code then Corrects it?
here is my php script :
init.php :
<?php
$db_name = "webapp";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
$con=mysqli_connect($server_name, $mysql_username, $mysql_password, $db_name);
if (!$con) {
echo "Connection Error ......." . mysqli_connect_error();
} else {
echo "<h3>Database connection Success .....</h3>";
}
?>
login.php :
<?php
require "init.php";
$user_name = "YASER";
$user_phone = "123456";
$sql_query = "select name from user_info where user_name like'$user_name'and
user_phone like'$user_phone';";
$result = mysqli_query($con,$sql_query);
if (mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_assoc($result);
$name = $row["name"];
echo "<h3> Hello And Wellcome" . $name . "</h3>";
} else {
echo " No Info Is Available .......";
}
?>
1st : First check that query is executing or failing
if(!$result){ echo mysqli_error($con); }
2nd : use = instead of like
$sql_query = "select name from user_info
where user_name='$user_name' and
user_phone='$user_phone'";
3rd : You need to give proper spacing In query
like'$user_name'and
^^^ ^^^
To
like '$user_name' and
You have error in your query.
try this to find error
$result = mysqli_query($con,$sql_query) or die(mysqli_error($con));
Your query should be like as follow...
'SELECT name FROM user_info WHERE user_name LIKE "'.$user_name.'" AND user_phone LIKE "'.$user_phone.'"';

Check if a value exists in MySQL with php

I've been looking around stackoverflow and wasn't able to ever find a way that'd actually work. I have a simple php application
//Database credentials
$servername = "localhost";
$username = "root";
$password = "password";
$database = "database";
// Create connection to database
$db = new mysqli($servername, $username, $password, $database);
// Check connection for errors
if ($db->connect_error) {
die("<h1>Connection to database failed: " . $db->connect_error) . "</h1>";
};
$username = $json['statuses'][0]['user']['screen_name'];
$userid = $json['statuses'][0]['user']['id_str'];
$sql = "SELECT * FROM log WHERE userid='" . $userid . "' LIMIT 1";
if ($db->query($sql)->num_rows > 0) {
echo "<h4>This user already exists</h4>";
} else {
//Put the userid into the database
$sql = "INSERT INTO log (userid) VALUES ('" . $userid . "')";
if ($db->query($sql) === TRUE) {
echo "<h4>Added " . $username . " to the database</h4>";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
}
Currently it seems to be hit or miss. It'll work sometimes, other times a record will exist, and it'll still insert the userid again creating duplicates.
Like said #tadman Your code is BAD. Data from variable $json is directly inserted into query - this is not good...
Simple test:
I set :
$userid = "111111111a";
query:
$sql = "SELECT * FROM log WHERE userid='111111111a' LIMIT 1";
return TRUE because, this user doesn't exists in db,
or
$userID ='111111111\' OR \'1=1';
query:
$sql = "SELECT * FROM log WHERE userid='111111111' OR '1=1' LIMIT 1";
return TRUE because 1=1 is always true.
If column userid is INT type, $userid value is converted to 111111111 and inserted into log table

Can't sign up using my DB

I need to make a Sign in form for my website. And I have to use MySQLi because MySQL will cause decaprated on my try.
So, here's the index.php code:
<?php
session_start();ob_start();
$con=mysqli_connect("localhost","root","","oos");
if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
if(isset($_POST['signin']))
{
$username = $_POST['userid'];
$pass = $_POST['password'];
$query1 = "select * from admintb where adID = '$username' and adPass = 'password' ";
$result1 = mysqli_query($con,$query1) or die;
$co=0;
while($row=mysqli_fetch_assoc($result1)) $co++;
if($co==1)
{
$_SESSION['a']=$username;
header("Location: main_menu.php");
}
} ?>
The problem is, when I make $username="admin" and $password = "admin", it will go to main_menu.php alright. But when I try to do as above, base on my database, it won't go to main_menu.php.
How can I sign in, go to the main_menu.php using ID from my database?
Sorry, I already checked it, it's a stupid mistake. Inside this snippet:
$username = $_POST['userid'];
$pass = $_POST['password'];
$query1 = "select * from admintb where adID = '$username' and adPass = 'password' ";
$result1 = mysqli_query($con,$query1) or die;
fix to this:
$query1 = "select * from admintb where adID = '$username' and adPass = '$pass' ";

Reducing MSQL Query to a specific session

Using the code below, I was able to display each username and trial 1/0 flag in the table. What I want to do is display the data only for the existing user so I can say something like "Hello USERNAME, you have TRIAL access..." etc...
We're using standard HTACESS as the un/pass to enter the info area.
What needs to change here to only show the existing user's session?
<?PHP
$user_name = "blahblahblah";
$password = "blahblahblah";
$database = "blahblahblah";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM member_auth";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_array($result) ) {
print $db_field['username'] . " : ";
print $db_field['trial'] . " <br> ";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
please don't use mysql_ functions.. look into PDO or MySQLi here: http://www.phptherightway.com/#databases
Update your query to only return specific user results.
Using Form POST:
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
Using URL Parameters:
$username = mysql_real_escape_string($_GET["username"]);
$password = mysql_real_escape_string($_GET["password"]);
So your SQL query will now look like:
$SQL = "SELECT * FROM member_auth WHERE username = '" . $username . "' AND password = '" . $password . "'";

PHP login script always returns "login failed"

I have to give users the ability to log in for an assignment. At first, it seemed to me this script was simple enough to work, but everytime I try to log in with an existing account it gives me the "login failed" message. I don't know where my mistake lies. It's a PostgreSQL database, I'll enclose an image of it below.
<?php
require 'databaseaccess.php';
try {
$conn = new PDO('pgsql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME,DB_PASSWORD);
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "\n";
phpinfo();
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$tablename = "users";
// sql-injection counter
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$qry = $conn->prepare("SELECT * FROM $tablename WHERE userid = :username and userpass = :password");
$qry->bindParam(':username', $username, PDO::PARAM_STR, 16);
$qry->bindParam(':password', $password, PDO::PARAM_STR, 16);
$qry->execute();
$result = pg_query($qry);
$count = pg_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if ($count == 1) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
header("location:logingelukt.php");
} elseif ($count = -1) {
echo "there has been an error";
} else{
print $count;
echo "login failed";
}
?>
I have no problems connecting to the database, so that's not an issue, it's just that it always sees $count as something else than zero. Another oddity is that the print $count command doesn't output anything.I use the account I made with postgresql outside of the page, which is just admin:admin. Also, I'm sure the right variables are getting passed from the form.
EDIT: After using var_dump($result), as advised by kingalligator, it seems that $result is indeed NULL, thus empty. I'm gonna try using fetch() instead of pg_query().
I think the issue is that you're mixing PDO and pg_ functions.
Replace:
$result = pg_query($qry);
$count = pg_num_rows($result);
With:
$result = $qry->fetchAll();
$count = count($result);
PDO Function reference can be found here: http://www.php.net/manual/en/class.pdostatement.php
Have you confirmed that you're actually getting data returned from your query? Try this:
var_dump($result);
To ensure that data is being returned from your query. You can still have a successful connection to a database, yet have a query that returns nothing.
You probably should check your column userid at WHERE clause. I don't know the table columns, but is strange that 'userid' has the name of the user in:
"SELECT * FROM $tablename WHERE userid = :username and userpass = :password"
Maybe it is causing the problem.

Categories