Mysqli returns the wrong data - php

I would like to echo out the values of the column username and tried it like this:
public function username_exists($username) {
$conn = new mysqli($this->servername, $this->username, $this->password, $this->db_name);
$result = mysqli_query($conn, "SELECT username FROM fe_users WHERE username = $username");
while ($row = mysqli_fetch_assoc($result)) {
echo $row["username"];
}
}
When I run this code, for some reason it always returns the string 33, which is also stored in my database but it is definitely not the value of the column username. Why am I getting this output and how can I display the username which is stored in the table fe_users?

You need to quotes around $username
SELECT username FROM fe_users WHERE username = '$username'"
Better use bind and prepare statement. It automatically escape your string and free from sql injection attack
/* prepare statement */
$stmt = $conn->prepare( "SELECT username FROM fe_users WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($col1);
/* fetch values */
while ($stmt->fetch()) {
printf("%s %s\n", $col1);
}
/* close statement */
$stmt->close();

Related

How can I make this a prepared Statements code?

I was under the impression that this was a prepared statement script, but it appears I was wrong. How can I turn this into one? What is a prepared statement?
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT Status FROM Users WHERE Username = ? AND Password = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $_GET['username'], $_GET['password']);
$stmt->execute();
$result = $stmt->get_result();
$rows = $result->fetch_all(MYSQLI_ASSOC);
if ($result->num_rows > 0) {
// output data of each row or remove while loop if you wish
while($row = $result->fetch_assoc()) {
echo "<b style='color:green'>Found</b>";
}
} else {
echo "0 results";
}
$conn->close();
?>
That's not using prepared statements. This is a basic example with no error/result checking:-
$sql = "SELECT Status FROM Users WHERE Username = ? AND Password = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $_GET['username'], $_GET['password']);
$stmt->execute();
$result = $stmt->get_result();
$rows = $result->fetch_all(MYSQLI_ASSOC);
However you should consider selecting on username only and retrieving the password for comparison. You should also hash your passwords in the database if you're not doing so. Use php's password_hash() and password_verify() for that. The former would help in hashing the password while the latter would be used to verify if the posted password from the html form or original source matches the hashed password
the syntax is
password_hash($_GET['password'], PASSWORD_DEFAULT);
password_verify($_GET['password'], $hashedPasswordFromDatabase);
make sure the column storing the password is varchar(60) at least.

PHP deleting a row with a string

I am trying to delete a row that matches a string that is passed in to the method.
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$data = array($_POST["username"]);
$stmt = $conn->prepare("DELETE FROM Table WHERE username = username=? ");
$stmt->execute($data);
I tried a few combinations of the SQL statement but cannot get one to work
// Store user input in a variable
$data = $_POST["username"];
// Prepare the query
$stmt = $conn->prepare("DELETE FROM Table WHERE username=:username");
// Bind the value
$stmt->bindValue(':username', $data, PDO::PARAM_STR);
// Execute the query
$success = $stmt->execute();
// If query succeeded, display the number of affected rows
if ($success) {
$affected_rows = $stmt->rowCount();
echo $affected_rows;
}
Spot the SQL error:
username = username=?
Should be
username = ?

using a value of a field from a table inside a query

I have a simple question. how can I use data stored in a field as a variable in a query?
in this example I want to use crypt and need the value inside password field of my database. how should I manage it.
$myusername=strtolower($myusername);
$query='SELECT * FROM auth '
."WHERE uname='$myusername' "
."and pword=crypt('$mypassword','pword')";
$result= mysqli_query($connection, $query);
if(mysqli_num_rows($result)>0)......
pword and uname are my field names inside the auth table. this is my first script in PHP and SQL.
If you want to refer to a field in the database, don't quote it:
$myusername = $connection->real_escape_string(strtolower($myusername));
$mypassword = $connection->real_escape_string($mypassword);
$query='SELECT * FROM auth'
."WHERE uname='$myusername'"
."and pword=crypt('$mypassword',pword)";
I suggest to use prepared statements instead:
$myusername = strtolower($myusername);
$sql = "SELECT * FROM auth HERE uname = ? and pword = crypt(?, 'pword')";
// prepare statement
$stmt = mysqli_prepare($connection, $sql);
if(!$stmt)die('can not prepare statement');
// supply parameter values:
mysqli_stmt_bind_param($stmt, 'ss', $myusername, $mypassword);
// execute
if(!mysqli_stmt_execute($stmt))die('can not execute statement');
// if there are rows...
if(mysqli_stmt_num_rows($stmt)){
// bind to variables
mysqli_stmt_bind_result($stmt, $col1, $col2 /* , colN */);
// output
while(mysqli_stmt_fetch($stmt)) {
var_dump($col1, $col2 /* , colN */);
}
}
// free statement
mysqli_stmt_close($stmt);
I suggest to read further:
SQL injection
How can I prevent SQL injection in PHP?
Assuming $connection is your database connection :
$connection = new mysqli("localhost", "my_db_user", "my_db_password", "my_table");
And assuming you want to get field user_id and the crypted password :
$myusername = $connection->real_escape_string(strtolower($myusername));
$query="SELECT user_id, crypt('{$mypassword}','pword') AS my_password FROM `auth`
WHERE uname='{$myusername}'
and pword=crypt('{$mypassword}','pword')";
$result = $connection->query($query);
if ($result !== false && $result->num_rows > 0) {
$row = $result->fetch_object();
$myUserID = $row->user_id;
$myPassword = $row->my_password;
}
Notes :
Enclose PHP variables inside string with {} for better practices.
You could enclosed query string within a pair of "" eventhough those
string take more than one rows.
Hopefully this help.

WHERE statement inside if condition in SQL

Can I do a WHERE clause inside an IF statement?
Like I want something like this:
$SQL = mysql_query("SELECT * FROM `table` ORDER BY `row` DESC");
$rows = mysql_fetch_array($SQL);
$email = $_SESSION['email_of_user'];
if($rows["row"] == "1" WHERE `row`='$email' : ?> (Pulls the logged in user's email)
Edit Server
<?php else : ?>
Add Server
<?php endif; ?>
Do I need (" where the WHERE statement is? Because I tried that and it didn't seem to work...
Or can I do it with an if condition inside of a where clause? Not sure of all these terms yet so correct me if I'm wrong...
You cannot mix up a query statement with PHP's statement. Instead write a query extracting desired results and check if there are any rows from that query.
I will show you an example:
$query = "SELECT * FROM `TABLE_NAME` WHERE `field` = '1' && `email`='$email'"; //Create similar query
$result = mysqli_query($query, $link); //Query the server
if(mysqli_num_rows($result)) { //Check if there are rows
$authenticated = true; //if there is, set a boolean variable to denote the authentication
}
//Then do what you want
if($authenticated) {
echo "Edit Server";
} else {
echo "Add Server";
}
Since Aaron has shown such a effort to encourage safe code in my example. Here is how you can do this securely. PDO Library provides options to bind params to the query statement in the safe way. So, here is how to do it.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //Create the connection
//Create the Query Statemetn
$sth = $dbh->prepare('SELECT * FROM `TABLE_NAME` WHERE field = :field AND email = :email');
//Binds Parameters in the safe way
$sth -> bindParam(':field', 1, PDO::PARAM_INT);
$sth -> bindParam(':email', $email, PDO::PARAM_STRING);
//Then Execute the statement
$sth->execute();
$result = $sth->fetchAll(); //This returns the result set as an associative array

PHP PDO how do i include fetch assoc and numrows

trying to convert all my old mysql_* operations into new and, from what i've heard, improved PDO, but this query wont seem to run successfully, I am trying to select all from the table PEOPLE where the username = $username (which has previously been declared $username = $_SESSION['username'];)
$query = "SELECT * FROM people WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
if ($num_rows == 1) {
// ...
}
THE WORKING CODE IS:
$query = "SELECT * FROM people
WHERE username=?";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $username);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
$user = $stmt->fetchObject();
if ($user) {
//do something
}
$stmt->fetchColumn does not fetch the number of rows; in this case it will fetch the first column from the first row of the result set. Since that will not be equal to 1 generally your test will fail.
In this case there is also no real need to count the number of returned rows because you are expecting either one or zero (if the username does not exist). So you can simply do:
$stmt->execute();
$user = $stmt->fetchObject();
if (!$user) {
// not found
}
else {
echo "User $user->username found!";
}
The if(!$user) test works because if there is no row to fetch $user will be false (see the documentation for fetchObject).
$query = "SELECT * FROM people WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
// do stuff
}
Use PDOStatement::rowCount as the num_rows and PDOStatement::fetch(PDO::FETCH_ASSOC) as fetch_assoc equivalent.
You want
if ($stmt->num_rows == 1) {
instead.

Categories