Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\login.php [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
i'm getting the following error
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\login.php
everything else work fine... except for this !
Here's my query :
<?php
$inputuser = $_POST["user"];
$inputpass = $_POST["pass"];
$user = "root";
$password = "";
$database = "share";
$connect = mysql_connect("localhost:3306",$user,$password);
#mysql_select_db($database) or ("Database not found");
$query = "SELECT * FROM 'users' WHERE 'username'= '$inputuser'";
$querypass = "SELECT * FROM 'users' WHERE 'password'= '$inputpass'";
$result = mysql_query($query);
$resultpass = mysql_query($querypass);
$row = mysql_fetch_array($result);
$rowpass = mysql_fetch_array($resultpass);
$serveruser = $row['user'];
$serverpass = $row['password'];
if ($serveruser && $serverpass) {
if (!$result) {
die ("Invalid Username/Password");
}
header('Location: Fail.php');
mysql_close();
if ($inputpass == $serverpass) {
header('Location: Home.php');
} else {
}
}
?>

Do not use mysql_* functions. They are deprecated.
You have an error in your SQL Syntax. Change your queries to this:
SELECT * FROM `users` WHERE `username`= '$inputuser';
SELECT * FROM `users` WHERE `password`= '$inputpass';
You must use backticks, ` and not ' quotes.
And please try to combine them like this:
SELECT * FROM `users` WHERE `username`= '$inputuser' AND `password`= '$inputpass';
What if there are two users with the same password? You cannot expect all the users to use different passwords right?
Other things. You are passing the user input directly to the SQL. This is very bad and leads to SQL Injection. So you need to sanitize the inputs before you can send it to the Database server:
$inputuser = mysql_real_escape_string($_POST["user"]);
$inputpass = mysql_real_escape_string($_POST["pass"]);
Again, do not use mysql_* functions.
Update the Code
Use the following code.
// single query
$query = "SELECT * FROM `users` WHERE `username`='$inputuser' AND `password`='$inputpass'";
// your original query
$query = "SELECT * FROM `users` WHERE `username`= '$inputuser'";
Final Code
<?php
$inputuser = mysql_real_escape_string($_POST["user"]);
$inputpass = mysql_real_escape_string($_POST["password"]);
$user = "root";
$password = "";
$database = "share";
$connect = mysql_connect("localhost", $user, $password);
#mysql_select_db($database) or ("Database not found");
$query = "SELECT * FROM `users` WHERE `username`= '$inputuser' AND `password`= '$inputpass'";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
header('Location: Home.php');
die();
}
else {
header('Location: Fail.php');
die ("Invalid Username/Password");
}
?>

Related

why i trying to update the data, but it show me the error on the line "$result=mysqli_query($connection,$query);"

I have a problem on this, I can't find where is the problem in my code, anyone help me, pls.
<?php
if($_POST['submit']) {
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query = "UPDATE users SET ";
$query .="username = '$username' ";
$query .="password = '$password' ";
$query .="WHERE id = $id";
$result = mysqli_query($connection, $query);
if(!$result) {
die ('QUERY FAILED' . mysqli_error($connection));
}
}
?>
I need to update the new data into MySQL, but it show me the error message:
Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'password='av' WHERE id='
Missing ',' in your query.
<?php
if($_POST['submit']) {
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query = "UPDATE users SET ";
$query .= "username = '$username', "; // missing ','
$query .= "password = '$password' ";
$query .= "WHERE id = $id";
$result = mysqli_query($connection, $query);
if(!$result) {
die ('QUERY FAILED' . mysqli_error($connection));
}
}
?>
The Update query should be :
UPDATE users SET username = 'username', password = 'password' where id = 1
As correctly pointed out by Majharul, the error is caused by the missing comma (,) between the columns listed in your SET clause. The error is almost always immediately preceding the part of the query returned in the error: password='av' WHERE id=.
More importantly, you should never store passwords in plain text, nor should you be simply concatenating strings and/or interpolating variables directly into your SQL. This is a very obvious SQL Injection vulnerability and easy to exploit. You should be using parameterized prepared statements to pass your variables into your query.
This is a simplistic example (validation of user input should be added) of how you might improve your code:
<?php
if($_POST['submit']) {
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$id = $_POST['id'];
/* Prepare your UPDATE statement */
$stmt = mysqli_prepare($connection, 'UPDATE users SET username = ?, password = ? WHERE id = ?');
/* Bind variables to parameters */
mysqli_stmt_bind_param($stmt, 'ssi', $username, $password, $id);
/* Execute the statement */
$result = mysqli_stmt_execute($stmt);
if(!$result) {
die ('QUERY FAILED' . mysqli_error($connection));
}
}
Please read PHP docs for password_hash() for more detailed explanation.

PHP Register Script - check user exists not working

I've got a problem with my PHP Registration Script that firstly checks, if the user exists.
It always outputs "false".
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$database = #mysql_connect("***********", "********", "******") or die("Can't connect to the server. Error: ".mysql_error());
//$username = mysql_real_escape_string($username);
$passwort = hash("sha256", $passwort);
$numrows = mysql_query("SELECT * FROM *******.mikgames WHERE username='".$username."' LIMIT 1");
$checkuserexists = mysql_num_rows($numrows);
if($checkuserexists==0) {
$abfrage = mysql_query("INSERT INTO *******.mikgames (username,passwort) VALUES ('$username', '$passwort')");
echo'true';
}
else {
echo'false';
}
?>
Edit: Now I'am using MySQLi and I've changed the code into this:
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$con = mysqli_connect('************','******','******') or die(mysqli_error());
mysqli_select_db($con, "*******") or die("cannot select DB");
$passwort = hash("sha256", $passwort);
$query = mysqli_query($con,"SELECT * FROM *******.mikgames WHERE username='".$username."'");
$result = mysqli_num_rows($query);
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames (username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
echo 'true';
}
else {
echo 'false';
}
?>
And it works.
You could go one step better and take an OOP approach using the PDO driver; PDO invokes security by allowing secure parameter binding and uses the SQL preferred functions.
Inside your pdo_driver.php file:
namespace ProjectName\App\Drivers;
if(!defined('IN_PROJECTNAME'))
{
die('No Script Kiddies Please...');
}
interface EntityContainer
{
public function query($statement, array $values = array());
}
class Entity extends \PDO implements EntityContainer
{
public function __construct(
$dsn = 'mysql:host=XXXX;dbname=XXXX', $user = 'XXXX', $pass = 'XXXX'
) {
try {
parent::__construct($dsn,$user,$pass);
} catch (PDOException $ex) {
die('FATAL ERROR: ' . $ex->getMessage());
}
}
public function query(
$statement, array $values = array()
) {
$smpt = parent::Prepare($statement);
(empty($values)) ? $smpt->execute() : $smpt->execute($values);
return $smpt;
}
}
Inside any other php file:
define('IN_PROJECTNAME', 0);
require_once dirname(__FILE__) . '/path/to/pdo_driver.php';
$container = array();
$container['Connection'] = new ProjectName\App\Drivers\Entity();
$username = $_GET['username'];
$passwort = $_GET['passwort'];
if(empty($container['Connection']->query('SELECT passwort FROM ******.mikgames WHERE username = ?', [$username])->fetch()['passwort'])) {
$container['Connection']->query('INSERT INTO ******.mikgames (username,passwort) VALUES (?, ?)', [$username,$passwort]);
}
Two Factors:
Firt Factor
You need to add an error output for debugging purposes:
$query = mysqli_query($con,"SELECT * FROM <tablename> WHERE
username='".$username."'") or die(mysqli_error($con));
I can't see a clear error with the information you have displayed here so far so you should also check what the value of $username acutally is and how closely it fits the value in the DB. Also read and take on board what the error output tells you.
Second Factor:
Your problem is you're running/articulating a query twice, here:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
You see $abfrage is a MySQL result object and you're then plugging it back into a MySQL query call, with the variable declaration $result. So your result is querying a query. This is an error.
What you probably want to do is use MySQLi_affected_rows to count how many rows have been inserted and run the appropriate IF clause:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_affected_rows($con);
echo 'true';
}
else {
echo 'false';
}
Use #mysql_***** for your ptoject.
$sql="SELECT * FROM table_name";
$result=#mysql_query($sql, $conn);
while ($name = # mysql_fetch_array($result)){
echo $name ['username'];
}
You just used simple mysql_***

PHP / MySQL: Login form doesn't work

I've got a login.php file which looks like this:
include "myfuncs.php";
$connect = dbConnection();
$username = $_POST["username"];
$passwort = md5($_POST["password"]);
$query = "SELECT username, password FROM user WHERE username LIKE '$username' LIMIT 1";
$ergebnis = mysql_query($query);
$row = mysql_fetch_object($result);
if($row->password == $passwort)
{
echo "Hi $username";
$_SESSION["username"] = $username;
echo "Login successfully";
}
else
{
echo "Login doesn't work";
}
and a myfuncs.php file which looks like this:
function dbConnection()
{
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
$db_connect = new mysqli($servername, $username, $password, $dbname);
if ($db_connect->connect_error)
{
die("Connection failed: " . $db_connect->connect_error);
}
return $db_connect;
}
Unfortunately the login form doesn't work - it always gives the error "Login doesn't work" even when the username and password matches with the database entry.
Arg, you are mixing a mysqli with class mysql functions. I dont think it works...
It works this way : PHP MySQLI
$stmt = $mysqli->prepare($query)
while ($stmt->fetch()) {
(...)
}
I see you have error in your variable name in line #6.
try this:
$query = "SELECT username, password FROM user WHERE username LIKE '$username' LIMIT 1";
$result= mysql_query($query);
$row = mysql_fetch_object($result);
There are several problems with your code. In myfuncs.php you use mysqli and after that, in your code you use mysql (without "i"). mysql (without "i") is deprecated, so you should use mysqli everywhere.
More than that, in your code you have:
$query = "SELECT username, password FROM user WHERE username LIKE '$username' LIMIT 1";
$ergebnis = mysql_query($query);
$row = mysql_fetch_object($result);
Please see the bold text from next two lines (it should be the same variable):
$ergebnis = mysql_query($query);
$row = mysql_fetch_object($result);
You should have
$result = mysql_query($query);
if you will use mysql.

php mysql query with hyphen character

I have a query problem with hyphen character.
$user = "test-user";
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
echo mysql_error(); //no error message
test-user record is in table but query result coming empty. Also mysql error message is empty. What is wrong?
EDIT:
Thank you for answers. I apologize to everyone. I found the problem and I see now the problem is not in the query. Problem coming form regex.
if (preg_match("/^[a-z0-9]+$/i", $user)) //dash character not in regex
{
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
}
I've corrected the problem as follows:
if (preg_match("/^[a-z0-9\-]+$/i", $user)) //added \- to regex for dash
{
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
}
Just use mysql_real_escape_string to escape the data string.
$user = "test-user";
$user = mysql_real_escape_string($user);
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
echo mysql_error(); //no error message
But I would also recommend using or die() syntax instead of the #mysql_query you have in place.
$user = "test-user";
$user = mysql_real_escape_string($user);
$q = mysql_query("SELECT id FROM table WHERE user='$user'") or die ("Error: " . mysql_error());
$p = mysql_query("SELECT id FROM table WHERE user='$user'");
if (!$p)
{
die('Could not query:' . mysql_error());
}
else
{
echo mysql_result($p>0);
}
try it
Try this:
$user = "test-user";
$q = mysql_query("SELECT id FROM `table` WHERE user='".$user."'")
or die(mysql_error());//no error message;
Full example with mysqli_:
$host = "";
$user = "";
$password = "";
$database = "";
$user_name_query = "test-user"; // If this value is from a form please read more about sql-injection.
// open connection to database
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
// SELECT QUERY
$query = "SELECT id FROM `table` WHERE user='".$user_name_query."'";
mysqli_query($link,$query) or die("Query failed");
}
// close connection to database
mysqli_close($link);
Any difference if you change the query to:
$q = mysql_query("SELECT id FROM table WHERE user='".$user."'");
Unless I'm having a very slow Sunday I think you're searching for the literal string $user rather than the variable value.

select request in php with errors

i'm trying to select data from mysql database with code in php but always i have errors.`
<?php
$dbhost = "localhost";
$dbuser = "";
$dbpass = "";
$db = "test";
$connect = mysql_connect($dbhost, $dbuser, $dbpass, $db)
or die ("connexion impossible");
mysql_select_db($db) or die ("selection de la base échoué");
$username = $_POST['username'];
$password = $_POST['password'];
query = mysql_query("SELECT * FROM table2 WHERE username= '$username' AND password='.$password'");
$num = mysql_num_rows($query);
if($num == 1) {
while($list = mysql_fetch_assoc($query)){
$output = $list;
echo json_encode($output);
}
mysql_close();
}
?>
errors:
Notice: Undefined variable: username in C:\wamp\www\projet\connect.php on line 11
Notice: Undefined variable: password in C:\wamp\www\projet\connect.php on line 11
Replace the line
query = mysql_query("SELECT * FROM table2 WHERE username= '$username' AND password='.$password'");
with
$query = mysql_query("SELECT * FROM table2 WHERE username= '".$username."' AND password='".$password."'");
You have missed the $ before variable query, and with some string concatenation problems
And please use PDO instead of deprecated mysql_*
there is extra dot before $password in mysql query and query should be $query as $query is variable.
query = mysql_query("SELECT * FROM table2 WHERE username= '$username' AND password='.$password'");
should be
$query = mysql_query("SELECT * FROM table2 WHERE username= '$username' AND password='$password'");

Categories