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);
Related
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I am using PHP with MySQli and I want to fetch a single row from the whole SQL DB, which fits in my condition. Just for a note, this is what my current database looks like :
I want to get that single row where, eg. txnid column's value == $txnid (a variable). I tried to build the SQL Query which would fit my requirements, and here's how it looks like : $sql = "SELECT * FROM 'table1' WHERE 'txnid' = " . $txnid;. When I raw-run this Query in phpMyAdmin, it works as expected. I just want to know, after I run the Query in PHP, how to fetch that row's data which came in as response from the Query using MySQLi?
This is the code which I am using to run the Query :
$servername = "localhost";
$username = "XXXXXXXXXXXXXX";
$password = "XXXXXXXXXXXXXX";
$dbname = "XXXXXXXXXXXXXXXX";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$txnid = $_GET['id'];
$sql = "SELECT * FROM `testtable1` WHERE `txnid` = " . $txnid;
if ($conn->query($sql) === TRUE) {
echo ""; //what should I do here, if I want to echo the 'date' param of the fetched row?
} else {
echo "Error: " . $sql . "<br>" . $conn->error . "<br>";
}
Add LIMIT 1 to the end of your query to produce a single row of data.
Your method is vulnerable to SQL injection. Use prepared statements to avoid this. Here are some links you can review:
What is SQL injection?
https://en.wikipedia.org/wiki/SQL_injection
https://phpdelusions.net/mysqli_examples/prepared_select
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8mb4");
$txnid= $_GET['name_of_txnid_input_field'];
// prepare and bind
$stmt = $conn->prepare("SELECT * FROM `testtable1` WHERE `txnid` = ? LIMIT 1");
$stmt->bind_param("i", $txnid);
// set parameters and execute
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['date_field_you_want_to_display'];
$txnid = $_POST['txnid'];
$sql = "SELECT * FROM tableName WHERE txnid = $txnid";
$result = $conn->query($sql);
Hi I'm trying to use prepared statements within functions. I have the following function which is supposed to return the details of a country in a DB based on inputting the ID of the country - I then use an array to get the company name after. I don't know how to output the data to be used in the array from the function when I use prepared statements. I know I'm missing something basic. Please see below.
function findCountryname($countryID){
include 'connect.php';
$stmt = $conn->prepare("SELECT * FROM countries WHERE id=? and
pic!='NULL'");
$stmt->bind_param("i", $countryID);
$stmt->execute();
}
The 'connect.php' file consists of the following:
<?php
global $conn, $dbname, $username,$servername, $password;
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "country";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
This was the original function:
function findCountryname($countryID){
$result = mysql_query("SELECT * FROM `countries` WHERE `id`=' $countryID '
and `pic` != 'nothing' ");
return $result;
}
There is no reason to use globals or an include inside a function. If you insist on procedural code, you should inject the mysqli object into the function as an argument.
After the statement execution, you need to retrieve the mysqli result object for manipulation. If you're just getting the first row, the below example will work. If you expect multiple rows, you will have to call fetch_assoc in a loop as it will only retrieve one row at a time.
function findCountryname($countryID, mysqli $conn) {
$stmt = $conn->prepare("SELECT * FROM countries WHERE id=? and pic!='NULL'");
$stmt->bind_param("i", $countryID);
$stmt->execute();
// Get the mysqli result object
$result = $stmt->get_result();
// Return the first row of data in an associative array
$data = $result->fetch_assoc()
return $data;
}
You can use mysqli's fetch_assoc to fetch the resulting data from the query and store it in an array, then return that array.
So your function now becomes :-
function findCountryname($countryID){
include 'connect.php';
$stmt = $conn->prepare("SELECT * FROM countries WHERE id=? and
pic!='NULL'");
$stmt->bind_param("i", $countryID);
$stmt->execute();
$data = $stmt->fetch_assoc();
return $data;
}
So here is my code:
$sql = "SELECT * FROM `items`";
$result = mysqli_query($conn, $sql);
while($prommes = mysql_fetch_array($result)){
}
When I'm running it. I'm getting this error:
mysql_fetch_array() expects parameter 1 to be resource.
Is it something wrong with my database?
And here is my connection which Irequire in the html document. Can it be something here which makes the query not working?
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// echo "Connected successfully";
You never select a database, as far as I can tell, so $result is not a resultset (because the query never executes properly). It is probably false instead. You can var_dump it to verify that. Try adding the database name in the query. If your database is named db, for example:
SELECT * FROM `db`.`items`;
If you don't want to explicitly specify the database name every time, you'll just want to add the database name to the MySQLi connection string, as shown:
http://php.net/manual/en/mysqli.query.php
In the while loop, mysql_fetch_array is incorrect. It should be
while($prommes = mysqli_fetch_array($result))
Additonally your connection needs to be
$conn = mysqli_connect($servername, $username, $password, $database);
where $database is the name of your database (not the hostname).
As an aside, this can be better avoided using an object orientated approach. So for example, your connection could be;
$conn = new mysqli($servername, $username, $password, $database);
and your query and loop could be;
$result = $conn->query($sql);
while($prommes = $result->fetch_array())
Hope this helps.
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 :)
Fatal error: Call to a member function prepare() on a non-object in
/home/melazabi/public_html/assigment/The/include/process.php on line
15
// check if the username exists in the database
// line 15 is the one below:
$statement = $conn->prepare("select * from users where username=? AND password=?");
//prepare statment is to try to stop sql injection
$statement->bindParam(1, $un);
$statement->bindParam (2, $pw);
$statement->execute();
As per what you shown in your comment:
You're using a mysql_* based connection
$conn = mysql_connect('localhost','admin','admin') or die("error2"); mysql_select_db("admin") or die("error");
with a PDO query.
You need to use: (replace with actual DB credentials)
$dbname = 'admin';
$username = 'admin';
$password = 'admin';
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
The error is telling you the your query failed for any number of reasons.
Your db connection failed, either authentication problem or complete failure to connect.
Your params are not defined correctly.
you can debug this by
print_r($statement->errorInfo());
this will give you what the error returned by sql was.
also make user variables are set. If i were to guess not having seen the rest of your code. you probably want $_POST['un'] and $_POST['pw']
echo $un;
echo $pw;
edit
connect to db:
$conn = new PDO('mysql:host='SERVERADDRESS';dbname=DBNAME;charset=utf8', 'USERNAME', 'PASSWORD');
then your query
$statement = $conn->prepare("select * from users where username=? AND password=?");
//prepare statment is to try to stop sql injection
$statement->bindParam(1, $un);
$statement->bindParam (2, $pw);
$statement->execute();