MySQL query not fetching results (PHP) - php

I have the following script with an SQL problem which is not working.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Freepaste";
$conn = mysqli_connect($servername, $username, $password,$dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$user = $_POST['user'];
$pass = $_POST['pass'];
echo $user." ".$pass;
$stmt = $conn->prepare("SELECT * FROM users where users.username= ? AND users.password = ?");
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$result = $stmt->get_result();
printf("Errormessage: %s\n", $mysqli->error);;
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<br>id: " . $row["username"]." Password ".$row["password"]. "<br>";
}
}
else {
echo "<br>0 results <br>";
printf("Errormessage: %s\n", $mysqli->error);
}
mysqli_close($conn);
?>
The statement without the "where" clause gets me all the results, so I know the keys are right. Also, I ran the query in MySQL and it is working fine. I tried adding "" to $user and $pass, still not working. I checked the names in HTML, they are correct too. What am I missing?
Here's the link to the HTML:
http://pastebin.com/CWLuafVq

You are missing the quotes (although you are saying you tried) i think it should have worked. Your query should be:
SELECT * FROM users where users.username='$user' AND users.password='$pass'
Your query is vulnerable to SQL injection and in order to avoid it (and avoid hassle like requiring quotes in SQL statement), you should use PreparedStatement.

For your example, you just need to put single quotes around $user and $pass in the query.
BUT!!!!!! Your query is open to SQL injection. You should change the way you write queries. Use bound parameters instead, then you can almost forget about that issue.
Example:
$stmt = $conn->prepare("SELECT * FROM users where users.username= ? AND users.password = ?");
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$result = $stmt->get_result();
See here for more information

As it stands, when your variables are put into the sql query, it ends up looking like this WHERE users.username=goelakash AN.... Without quotes around username and password, mysql is going to think you're comparing two columns.
What your query needs to look like is this.
$sql = "SELECT * FROM users where users.username=\"$user\" AND users.password=\"$pass\"";
Do yourself a huge favor, and put mysqli_error() calls after your calls to mysqli_query(). These will tell you exactly what mysql is crying about.
It is also worth noting that your queries are open to sql injection and you should take a look at prepared statements to mitigate that.

make sure your database password is 'root'? If yes then follow the query string
$sql = "SELECT * FROM users WHERE users.username='$user' AND users.password='$pass'";
just replace it. I think it will work fine :)

Related

SQL Prepared Statement Error on my Search form

I am finding it difficult to write a SQL prepared statement for my search form, can I get help on fixing it? Everything works great without a SQL prepared bind statement but am sure it's not so secure.
Here is my CODE:
<?php
// Define Database connection parameters
$dbserver = "localhost";
$username = "root";
$password = "";
$dbname = "student";
// Lets Connect to theDatabase Table, But if there is an Error lets tell before its too late to figured
$conn = mysqli_connect ( $dbserver, $username, $password, $dbname ) or die ( ' I can not connect to the database ' );
// Its time to Capture the varibles and user inpute from the form , also we need to sanitize the input to avoid SQL Injection
$study_group = mysqli_real_escape_string ( $conn, $_POST['matric_number']);
/* Lets try to use bind Statement to reduce further hacking
I am also avoiding using "LIKE" Clause because IVariable direct Exact results so will be using the Direct Varible
*/
$sql = $conn->prepare (" SELECT * FROM study_circle WHERE matric = ? ") ;
$sql->bind_param('s', $study_group);
$sql ->execute();
$results = mysqli_query ($conn, $sql);
$mysqlResults = mysqli_num_rows ($results);
if ( $mysqlResults > 0 )
{
while ( $row = mysqli_fetch_assoc ( $results ))
{
// Display results in table form
echo " <div>
<h4> ".$row['full_name']."</h4>
</div>";
}
} else {
echo " Please Ensure your Matric Number is correct, We can not find anything relting to your data";
}
if you use prepared statement you should not use mysqli_real_escape_string
Try comment the mysqli_real_escape_string row and use $_POST['matric_number'] directly in bind_param
// $study_group = mysqli_real_escape_string ( $conn, $_POST['matric_number']);
/* Lets try to use bind Statement to reduce further hacking
I am also avoiding using "LIKE" Clause because IVariable direct Exact results so will be using the Direct Varible
*/
$sql = $conn->prepare (" SELECT * FROM study_circle WHERE matric = ? ") ;
$sql->bind_param('s', $_POST['matric_number']);
$sql ->execute();
The binding param and prepared statement prevents SQL injection so you don't need mysqli_real_escape_string operation

Prepared Statements Select with Variables - php

Trying to just set up something to verify that username = password via num_rows = 1.
Trying to use prepared statements, that I have never used before and i'm missing something. Where does the var in bind_results('s',$variable) come from??
Also, its just not working for me.
<?php
require ($_SERVER['DOCUMENT_ROOT'].'/db-connect.php');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user = $_POST['username'];
//$user = $mysqli->real_escape_string($user);//
$password = $_POST['password'];
//$password = $mysqli->real_escape_string($password);//
if ($stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?")) {
$stmt->bind_result('ss', $username);
$stmt->execute();
$result = $stmt->num_rows;
echo $result;
$stmt->close();
}
$mysqli->close();
?>
I see three problems with this:
$stmt->bind_result('ss', $username);
First, bind_result PHP documentation:
"Binds columns in the result set to variables."
I think you're looking for bind_param. PHP documentation:
"Bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare()."
Second, your statement has two parameter markers (?), your bind statement indicates two strings (ss), but you provide only one variable ($username).
Third, $username is not what you're getting from $_POST['username']. You've assigned that to $user. $username is for your database connection.
I think it should work for you with this line instead:
$stmt->bind_param('ss', $user, $password);

Why is the data not inserted into mysql database after submitting php nor is it giving out any error?

My code is below, I don't know what is wrong with my code, it says data submitted but not inserted into mysql database when I see in phpmyadmin
<?php
$dbhost = 'localhost';
$dbuser = 'Krishna';
$dbpass = 'xxxx';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
session_start();
if (isset($_POST['submit'])){
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
}
mysqli_select_db($conn, "krishna");
$sql = "INSERT INTO contact_us (name, email, sub, mess)
VALUES ('$_POST[name]','$_POST[email]','$_POST[sub]','$_POST[mess]')";
if(! $sql) {
die('Error: ' . mysqli_error());
}
echo "1 Record Added to Table\n";
echo "<a href='contactForm.html'>Back to main page</a>";
mysqli_close($conn);
?>
First let me start by saying you could do this in an attempt to learn how to use SQL which I also did when I was first learning but then realized ...
This method is subject to SQL injection attacks and should not be used. Directly taking any user input without sanitizing it first is critical mistake that can lead security vulnerabilities.
We now have tools like PDO statements which prepare your SQL for entry into a databases. Please consider using a similar tool which prepares your statements when getting anything from a user.
Users are not to be trusted. In the code below when you bindValue it takes the variable $id and removes anything harmful.
<?php
$stmt = $db->prepare("SELECT * FROM table WHERE id=? AND name=?");
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->bindValue(2, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
See this link for the source of the code above and a tutorial on PDO. There are probably better tutorials out there though.
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

How to prevent weird user inputs from breaking things in queries?

Is there a good standard solution to deal with characters like ' and " from being used in user inputs on a web platform?
I'm using php for a webpage and if I have, for example, a search bar which have the following query behind it.
$sql = "select * from aTable where aColumn like '%".$searchedKeyword."%'";
If I search for like Greg's icecream the ' will break the script. Also, I'm guessing if I search for something like 1' or ID>0 my script will have a false effect.
What is the common solution here? Do you usually filter away undesired characters, or is there maybe some method or similiar built-in to php?
You can us PDO and prepared statements to prevent SQL injection.
http://php.net/manual/en/pdo.prepared-statements.php
$searchedKeyword = "mykeyword";
//Database details
$db = 'testdb';
$username = 'username';
$password = 'password';
//Connect to database using PDO (mysql)
try {
$dbh = new PDO('mysql:host=localhost;dbname='.$db, $username, $password);
} catch (PDOException $e) {
var_dump("error: $e");
}
//Prepared SQL with placeholder ":searchedKeyword"
$sql = "select * from aTable where aColumn like '%:searchedKeyword%'";
$sth = $dbh->prepare($sql);
//Bind parameter ":searchedKeyword" to variable $searchedKeyword
$sth->bindParam(':searchedKeyword', $searchedKeyword);
//Execute query
$sth->execute();
//Get results
$result = $sth->fetchAll(); //fetches all results where there's a match

MSQLI Having Trouble with num_rows

I am having trouble returning the number of rows. I want my code to check if a username exists, and if it does then return an error. The way I am going about this is if num_rows returns a number larger than 0. I haven't implemented that part yet, I am just trying to get it to return the number of rows right now. Here is my current code:
$hostname = ''; //SET SERVER/HOSTNAME
$dbusername = ''; //SET DATABASE USERNAME
$dbname = ''; //SET DATABASE NAME
$dbpassword = ''; //SET DATABASE USERNAME
$link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
if (!$link)
{
$systemerror = 'Connect Error' . mysqli_connect_errno() . mysqli_connect_error();
$error = "there has been an error";
}
$sql = "SELECT username FROM affiliates WHERE username = $username";
$result = mysqli_query($link, $sql, MYSQLI_USE_RESULT);
if (!result)
{
$error = "There was an error with our system. Please contact All Choice Dental or wait a few minutes. Thank you.";
goto error;
}
$row_cnt = $result->num_rows;
echo $row_cnt;
I don't even get zero back for num_rows, so something has to be wrong. I know I can connect to the database, because I can Insert rows using the same connection.
$username is never defined in your code, so the query comes out as
SELECT username FROM ... username =
As well, since a username is likely to be a string, you're also lacking quotes around that variable, so even if it was set, the query would still be wrong. e.g.
$username = 'fred';
would produce
SELECT username FROM affiliates WHERE username = fred
and you're not likely to have a fred field in your affiliates table. The field should be quoted:
SELECT username FROM ... WHERE username = '$username';
and you should seriously consider using prepared statements instead, as this sort of construct is vulnerable to SQL injection attacks.
You're mixing MySQLi OOP and Procedural - which is bad coding style.
To get the number of rows procedurally, use mysqli_num_rows($result)

Categories