can't get result from sql database [duplicate] - php

This question already has an answer here:
I cannot get my login form to connect interact properly with mySQL database [closed]
(1 answer)
Closed 6 years ago.
I am very new to php and I am trying to create a login system. Here is my code
<?php
$con=mysqli_connect("XXXXXXX","XXXXXXXX","XXXXXXXXX","XXXXXXXXXX");
if (!$con)
{
echo "failed to connect";
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT userID FROM users WHERE username = $username and password = $password;";
if (!$sql) {
echo 'query invalid'.mysql_error();
}
$result = mysql_query($sql);
echo "$result";
$row = mysqli_fetch_array($sql, MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
mysql_close($con);
?>
I am sure there is no problem with the connection. But my result is not showing up and there is no error message. Previously I had an IF statement that perform further action if the result comes back. Since I am trying to figure out what is going on, I just deleted that part. Somebody please help. Many thanks

You're missing the single quotes around the variables, and also you're using mysql mixed with mysqli, which will not work.
$sql = "SELECT userID FROM users WHERE username = '$username' and password = '$password';";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($sql); // same as fetch_array with MYSQLI_ASSOC
$active = $row['active'];
$count = mysqli_num_rows($result);
You don't need mysql_close at the end, but if you want to use it, it's mysqli_close($con);
Keep in mind this is unsafe.
Use this function to filter user input:
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
Read this to make sure your code follows the security standards.

I recommend this.
$sql = "SELECT userID FROM users
WHERE username = " ._sql($username) ." and password = " ._sql($password);
// generate sql safe string function
function _sql($txt) {
if ($txt === null || $txt === "")
return "NULL";
if (substr($txt, 0, 2) == "##")
return substr($txt, 2);
//$txt = str_replace("'", "''", $txt);
$txt = mysql_real_escape_string($txt);
return "'" . $txt . "'";
}

Related

Php mysqli user_exists not working at all

I have tryed this many many times and i don't get why this don't work. Because of this my registeration pages pass all usernames. I have no idea what is wrong. Sorry about my bad english i am really tired and desperate
function user_exists($username){
$username = htmlspecialchars($username);
$sql = "SELECT username FROM ***** WHERE username = '$username'";
$result = mysqli_query($GLOBALS['$db'], $sql);
if(mysqli_num_rows($result) > 0){
$errors[] = 'Käyttäjätunnus \''. $_POST['username'] . '\' on jo otettu.';
}
}
I am calling that function like this:
if(user_exists($_POST['username']) === true){
$errors[] = 'Käyttäjätunnus \''. $_POST['username'] . '\' on jo otettu.';
}
Well, let's clean this up some
function user_exists(mysqli $db, $username){
$username = htmlspecialchars($username);
$sql = "SELECT username FROM ***** WHERE username = ?";
$prep = $db->prepare($sql);
$prep->bind_param('s', $username);
$prep->execute();
$result = $prep->get_results();
$errors = [];
if($result->num_rows > 0){
$errors[] = 'Käyttäjätunnus \''. $username . '\' on jo otettu.';
}
return $errors;
}
First, you need to inject your DB connection into the function. Avoid using globals.
Second, we're switching to a prepared statement. Solves the SQL injection problem.
Third, we're returning an array. Your errors will never show up the way you were doing it. You can pick how/what gets returned, but, again, we don't want globals.

How to get started debugging a PHP script

I am pretty new to PHP, so debugging isn't really something I am familiar with when it comes to PHP.
I am using php/javascript(ajax) to change a users password for my website.
So basically, when I log in and try to change my password. The code breaks at the first echo. So the password that I am entering into the form does not match the password in the database. But, I am using the same hash method and everything. If anyone has any ideas, let me know. Thanks!
if(isset($_POST["u"])) {
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
$oldpasshash = md5($_POST["cp"]);
$newpasshash = md5($_POST["cnp"]);
$sql = "SELECT id, username, password FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_id = $row["id"];
$db_username = $row["username"];
$db_password = $row["password"];
if($db_password != $oldpasshash){
echo "no_exist";
exit();
} else {
$sql = "UPDATE users SET password='$newpasshash', WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
}
$sql = "SELECT id, username, password FROM users WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_newpass = $row[3];
if($db_newpass == $newpasshash) {
echo "success";
exit();
} else {
echo "pass_failed";
exit();
}
}
Look at your first two lines of code:
if(isset($_POST["u"])) {
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
You check if $_POST['u'] isset then you use $_GET['u'].
FYI, you are injecting $u directly into the mysql statement, don't do this.
You are using mysqli_fetch_row and accessing the table fields via field name. That is wrong.
mysqli_fetch_row fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero).
So you have to use
$db_id = $row[0];
$db_username = $row[1];
$db_password = $row[2];

comparing a password to a hash queried from database?

I send a password to php to get compared to the hash stored in the database.
my php is:
$enteredUser = $_POST["username"];
$enteredPass = $_POST["password"];
$query = mysqli_query($con, "SELECT passhash FROM user WHERE `username` = '$enteredUser'");
$passHash = mysql_result($query, 0);
if(password_verify($enteredPass, $passHash)){
echo "success";
}else{
echo "failure";
}
I also tried using mysqli_fetch_array() as well, but it still doesn't work. Does anyone know why this isn't working? thanks in advance to anyone who can help. (on a side note, $passHash returns null)
You are mixing two extensions, mysqli and mysql - mysqli_query and then mysql_result.
You are also open to SQL injection and should be sanitising your POST input before passing it directly to MySQL.
mysqli_query returns a result object and you then need to fetch the results from that object.
mysqli_fetch_row will return one row.
$enteredUser = $_POST["username"];
$enteredPass = $_POST["password"];
//...
$resultset = mysqli_query($con, "SELECT passhash FROM user WHERE `username` = '$enteredUser'");
$result = mysqli_fetch_row($resultset);
if(password_verify($enteredPass,$result[0])){
echo "success";
}else{
echo "failure";
}
I did solve my own problem with a simple while loop, i guess it will work fine, thanks everyone for your input:
$passHash = '';
while ($row = mysqli_fetch_array($query)) {
$passHash .= $row["passhash"];
}
Give this a try:
$enteredUser = mysqli_real_escape_string($con,$_POST["username"]);
$enteredPass = mysqli_real_escape_string($con,$_POST["password"]);
$sql = "SELECT * FROM `user` WHERE `username` = '$enteredUser'";
$result = $con->query($sql);
if ($result->num_rows === 1) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (password_verify($enteredPass, $row['passhash']))
{
echo "Success";
}
else {
echo "Sorry";
}

getting mysql_numrows(): supplied argument is not a valid MySQL result resource

I am trying to create a simple process that checks if a username is taken already during the login process.
I have a simple php script that querys the database and then i check to see if there are any results and echos a response to the user
the full error that i get is:
mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home1/tbronson/public_html/sandbox/uname_check.php on line 9
The entire php script is:
<?php
$user = "(removed for security)";
$pass = "(removed for security)";
$db = "budgetbidders_users";
$con = mysqli_connect($host,$user,$pass,$db);
$uname = strip_tags( trim( $_POST['uname'] ) );
$result = mysqli_query($con,"SELECT * FROM `users` WHERE uname = '" .$uname . '");
$numrows = mysql_num_rows($result); //line 9
if ($numrows > 0) {
$end_result = "Username already taken";
}
else {
$end_result = "";
}
echo $end_result;
?>
I have searched for hours and tried multiple variations, this seems to be the closest to correct that i can find, thank you for your help!
There were a few errors in your code.
The following line has a missing double-quote before the single quote for $uname:
$result = mysqli_query($con,"SELECT * FROM `users`
WHERE uname = '" .$uname . '");
^
However it would be better to use prepared statements or PDO along or you can use:
WHERE uname = '$uname' // instead
Plus, you're mixing the deprecated mysql_* function with the mysqli_* functions.
mysqli_query and mysqli_num_rows() where mysql_num_rows() needs to be changed to mysqli_num_rows
I also suggest you change:
$uname = strip_tags( trim( $_POST['uname'] ) );
to:
$uname = mysqli_real_escape_string($con, $_POST['uname']);
And:
WHERE uname = '" .$uname . "'
to:
WHERE uname = '$uname'
You can make any modifications you wish, both will work. Do read this article on SO on how to prevent SQL injection.
Give this a try now:
<?php
$user = "(removed for security)";
$pass = "(removed for security)";
$db = "budgetbidders_users";
$con = mysqli_connect($host,$user,$pass,$db);
// the line below is better to use
$uname = mysqli_real_escape_string($con, $_POST['uname']);
// this is your original line of code which will work also
// $uname = strip_tags( trim( $_POST['uname'] ) );
$result = mysqli_query($con,"SELECT * FROM `users` WHERE uname = '" .$uname . "' ");
$numrows = mysqli_num_rows($result); //line 9
if ($numrows > 0) {
$end_result = "Username already taken";
} else {
$end_result = "";
}
echo $end_result;
?>
That is beacase u are using mysql_ instead of mysqli_
try this
$numrows = mysqli_num_rows($result):
You cannot mix mysql_* and mysqli_* syntax.
In your case you need:
$numrows = mysqli_num_rows($result);
And you have a syntax error on the line before it (a missing quote).

Can anyone help me figure out the meaning of this php error message? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can anyone help me figure out what is wrong with this code?
Here is my code
$con = mysql_connect("localhost", "root", '');
if (!$con) {
die('Cannot make a connection');
}
mysql_select_db('yumbox_table', $con) or die('Cannot make a connection');
isset($_POST['user_name'], $_POST['password'], $_POST['user_type']);
$data = mysql_query("SELECT *
FROM users
WHERE user_name == ($_POST['user_name'])
AND ($_POST['password'])
AND ($_POST['user_type'])") or die(mysql_error());
$info = mysql_fetch_array($data);
$count = mysql_numrows($data);
if ($count == 1) {
echo("Success!!");
} else {
echo("BIG FRIGGIN FAILURE!!");
}
mysql_close($con);
Whenever I run this code, I receive the following message:
You need to escape your POST values before you insert put them into your query. You should escape your POST values before you use them in a database query.
Instead of this:
$data = mysql_query("SELECT * from users where user_name == ($_POST['user_name']) and ($_POST['password']) and ($_POST['user_type'])"
Do this:
$user_name = mysql_real_escape_string($_POST['user_name']);
$password = mysql_real_escape_string($_POST['password']);
$user_type = mysql_real_escape_string($_POST['user_type']);
$data = mysql_query("SELECT * FROM users WHERE user_name == '$user_name' AND password == '$password' AND user_type == '$user_type'");
Note that I am assuming your columns in the table are 'user_name', 'password', and 'user_type'.
if(isset($_POST['user_name'], $_POST['password'], $_POST['user_type'])){
$data = mysql_query("SELECT * from users
where user_name = '".mysql_real_escape_string($_POST['user_name'])."' and
password = '".mysql_real_escape_string($_POST['password'])."' and
user_type = '".mysql_real_escape_string($_POST['user_type'])."' ");
if(mysql_numrows($data) == 1) {
$info = mysql_fetch_array($data);
echo("Success!!");
} else {
echo("BIG FRIGGIN FAILURE!!");
}
}
else{
echo "Required Data Missing";
}
mysql_close($con);
You need to post the error for more details. But a few things I noticed was
mysql_query("SELECT * from users where user_name == ($_POST['user_name']) and ($_POST['password']) and ($_POST['user_type'])")
You need to change this to
//do escaping here. See note below.
$username = isset($_POST['user_name']) ? mysql_real_escape($_POST['user_name']) : '';
$pass = isset($_POST['password']) ? mysql_real_escape($_POST['password']) : '';
$type = isset($_POST['user_type']) ? mysql_real_escape($_POST['user_type']) : '';
mysql_query("SELECT * from users where user_name = '{$username}' AND password = '{$pass}' AND user_type = '{$type}'")
You need to escape values
MySQL comparisons are = and not == (thanks for pointing that out #jeremysawesome)
You need to check the column against your POST value
You also have an SQL injection vulnerability. Please at least use mysql_real_escape. Better yet, switch to PDO
You need to assign your isset check to a variable and check it. Otherwise it's just a waste.

Categories