I have a big problem. I wrote a simple $_GET system
$query = mysql_query("SELECT * FROM `users`");
while ($row = mysql_fetch_array($query)) {
if($_GET['user'] == $row['user_seo']) {
echo 'user exists';
} else {
echo 'No users found';
}
}
If user don't exists in table it display 'No users found' otherwise it display No users found user exists No users found. 2 times it display "No users found" but user exists with that seo in database table. Thanks.
database screen http://prntscr.com/2ddqu4
You are looping over all your users so you will get multiple messages.
You should add a WHERE condition to your query to check only for the required user and switch to PDO or mysqli with prepared statements.
Something like (in PDO):
$query = 'SELECT * FROM `users` WHERE `user_seo`=:user';
$db->prepare($query);
$db->execute(array(':user' => $_GET['user']));
// etc.
Try replacing mysql_fetch_array with mysql_fetch_assoc
Also I would strongly recommend using either PDO or mysqli and prepared statements
Safely find the user with mysqli:
if (isset($_GET['user'])) {
$user = $_GET['user'];
$connection = mysqli_connect($Host, $Username, $Password) or die(mysqli_error());
mysqli_select_db($connection, $database) or die(mysqli_error());
$user = mysqli_real_escape_string($connection, $user);
if (!is_numeric($user)) {
$user = "'$user'";
}
$sql = "SELECT * FROM `users` WHERE `user_seo`=$user;";
$result = mysqli_query($connection, $sql);
if ($result) {
$user = mysql_fetch_assoc($result)) {
if ($user) {
// User found
// Do something with info like:
$userName = $user['name'];
} else {
// User NOT found
}
mysql_free_result($result);
} else {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
}
You better may use an sql like this:
SELECT * FROM users WHERE user_seo='".$_GET['user']."'; And forget about looping all the rows.
EDIT: but better use PDO or Mysqli and prepared statements
Related
I am trying to create an override feature where users type in existing login credentials, verify that a result row is returned matching those credentials, and then verifying that the user has the override role assigned to them. If both MySQL statements return true, I want to run the final query to delete a row from the coded table.
With my current code, the program passes the first if statement and runs the second SELECT statement. Then, it appears to run the second if to moved to the third SELECT statement. However, on the third if statement, the DELETE statement isn't successful.
I think I have a few issues:
I don't know if I'm properly comparing the passwords.
Could the problem be caused by the nested if statements?
Is my problem 'if ($result1) {...}' (assuming that result1 will return true as long as the SELECT statement successfully ran with 0 results returned)?
Either way, I'm not entirely sure of the best way to fix the(se) issue(s).
NOTE:: Through testing, I have confirmed that:
My variables are successfully $_POSTing and of the correct datatypes.
With just the first if/else statement, the alerted response was always a "success" result, even with incorrect credentials entered.
All help is appreciated!!
MY CODE:
PHP:
<?php
include('[db connection page]');
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overrideUsername = $_POST['overrideUsername'];
$overridePassword = $_POST['overridePassword'];
$overrideUniqueID = $_POST['overrideUniqueID'];
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT * FROM users WHERE (users.login = \"".mysqli_real_escape_string($overrideUsername)."\") AND (users.password = ENCODE(\"".mysqli_real_escape_string(overridePassword)."\",\"".mysqli_real_escape_string(ENCRYPTION_SEED)."\"))";
$result1 = $conn->query($sql1);
if ($result1) {
$sql2 = "SELECT * FROM users INNER JOIN rolestousers ON (users.id=rolestousers.userid) WHERE (users.login = \"".mysqli_real_escape_string($overrideUsername)."\") AND (users.password =ENCODE(\"".mysqli_real_escape_string(overridePassword)."\",\"".mysqli_real_escape_string(ENCRYPTION_SEED)."\")) AND (rolestousers.roleid = '154')";
$result2 = $conn->query($sql2);
if ($result2) {
$sql3 = "DELETE * FROM locator_time_track_out WHERE locator_time_track_out.uniqueid = '.$overrideUniqueID'";
$result3 = $conn->query($sql3);
if ($result3) {
echo 'Override Successful! Please scan the unit again to close it out.';
} else {
echo 'Could Not Delete Record from the Table.';
}//End $sql3 num_rows if.
} else {
echo 'User does not have override permission. Please contact the IT Department.';
}//End $sql2 num_rows if.
} else {
echo 'Your login information is incorrect. Please try again. If the issue persists, contact the IT Department.';
}//End $sql1 num_romws if.
//Free the result variable.
$result1->free();
$result2->free();
$result3->free();
//Close the Database connection.
$conn->close();
}//End If statement
UPDATE:
This is the code file I was originally using for the override feature. However, it of course fails for an incorrect password...
include('[db connection file name');
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overrideUsername = $_POST['overrideUsername'];
$overridePassword = $_POST['overridePassword'];
$overrideUniqueID = $_POST['overrideUniqueID'];
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT * FROM users WHERE (users.login = ?) AND (users.password = ?)";
$stmt1 = $conn->prepare($sql1);
$stmt1->bind_param('ss', $overrideUsername, $overridePassword);
$stmt1->execute();
$stmt1->store_result();
if ($stmt1->num_rows == 1) {
$sql2 = "SELECT * FROM users INNER JOIN rolestousers ON (users.id=rolestousers.userid) WHERE (users.login = ?) AND (users.password = ?) AND (rolestousers.roleid = '154')";
$stmt2 = $conn->prepare($sql2);
$stmt2->bind_param('ss', $overrideUsername, $overridePassword);
$stmt2->execute();
$stmt2->store_result();
if ($stmt2->num_rows == 1) {
$sql3 = "DELETE * FROM locator_time_track_out WHERE locator_time_track_out.uniqueid = ?";
$stmt3 = $conn->prepare($sql2);
$stmt3->bind_param('s', $overrideUniqueID);
$stmt3->execute();
$stmt3->store_result();
if ($stmt3->num_rows == 1) {
echo 'Override Successful! Please scan the unit again to close it out.';
} else {
echo 'Could Not Delete Record from the Table.';
}//End $sql3 num_rows if.
} else {
echo 'User does not have override permission. Please contact the IT Department at ext. 0102.';
}//End $sql2 num_rows if.
} else {
echo 'Your login information is incorrect. Please try again. If the issue persists, contact the IT Department at ext. 0102.';
}//End $sql1 num_romws if.
//Free the result variable.
$stmt1->free();
$stmt2->free();
$stmt3->free();
//Close the Database connection.
$conn->close();
}//End If statement
So I am grabbing the amount of rows in a specific table where the username is already in the database like so:
$second_sql = $db->prepare("SELECT * FROM users WHERE username = :username");
$second_sql->bindParam(':username', $username);
$second_sql->execute();
if($second_sql->rowCount() == 1) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
The problem is it's not working. If you need more of the script just tell me.
Some databases does not report the row count with PDO->rowCount() method.
SQLite, for instance.
So don't use rowCount(); doing so makes your code less portable.
Instead use the COUNT(*) function in your query, and store the result in a variable.
Finally, use that variable to fetch the one and only column (users) using the fetchColumn() method.
So you can play with this:
try {
$second_sql = $db->prepare("SELECT COUNT(*) from users WHERE username = :username");
$second_sql->bindParam(':username', $username, PDO::PARAM_STR);
$second_sql->execute();
$count = $second_sql->fetchColumn();
} catch (PDOException $e) {
// Here you can log your error
// or send an email
// Never echo this exception on production
// Only on development fase
echo "Error: " . $e->getMessage();
}
if ($count) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
Perhaps you wanna test you condition for a single row:
if ($count == 1)
Hope this helps you.
Cheers!
I am trying to make this query using PDO and it is returning and error.I have already verified the connection to the database.
function temperaturaMedia($data_inicio,$data_final,$ema)
{
$db = 'sensorzapp_db';
$query = "SELECT
DATE(DTM) AS 'Dia',
ROUND(AVG(TMP),1) AS 'Temp. Med.'
FROM dados_meteo
WHERE POM = '$ema'
AND DATE(DTM) BETWEEN '$data_inicio' AND '$data_final'
GROUP BY DATE(DTM)";
$stmt = $db->query($query);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
You are trying to execute a query on a string, you need to connect to the database, like this:
function temperaturaMedia($data_inicio,$data_final,$ema)
{
try {
$db = new PDO("mysql:host=localhost;dbname=sensorzapp_db","user","password");
} catch($ex) { die("Connection failed"); } // To not disclosure username & password when connection fails (look at the red box on http://www.php.net/manual/de/pdo.connections.php)
$query = "SELECT
DATE(DTM) AS 'Dia',
ROUND(AVG(TMP),1) AS 'Temp. Med.'
FROM dados_meteo
WHERE POM = '$ema'
AND DATE(DTM) BETWEEN '$data_inicio' AND '$data_final'
GROUP BY DATE(DTM)";
$stmt = $db->query($query);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
If i've database table with users(name,job) (john,Poster) and i made query with MySQLi using this code and that would works.
$job = "Poster";
$statement = $con->prepare("SELECT * FROM users WHERE `job` = ?");
$statement->bind_param("s",$job);
$statement->execute();
$statement->bind_result($name,$job);
while ($statement->fetch()){
echo $name;
}
what if i made $job = "NOTHING"; and there was no results then how can i show error such as echo "No reuslts found"; !! the above code if $job was not found it will show nothing. ~ thanks
EDIT
this one didn't worked too :(
$job = "NOTHING"; // should not found and should gives error
if ($statement = $con->prepare("SELECT * FROM users WHERE `job` = ?")){
$statement->bind_param("s",$job);
$statement->execute();
$statement->bind_result($name,$job);
while ($statement->fetch()){
echo $name;
}
}else{
echo "No results found dude";
}
Do not use mysqli. It is unusable with prepared statements.
Use PDO instead.
With PDO your code would be shorter, sensible and works.
$statement = $con->prepare("SELECT * FROM users WHERE `job` = ?");
$statement->execute(array($job));
if ($row = $statement->fetch()){
echo $row['name'];
} else {
echo "No results found dude";
}
You need to create a connection first. Something like this
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'dbuser';
$pass = 'dbpass';
$con = new PDO($dsn, $user, $pass);
You can see details on the manual page
As a further step you can move to some helper library, which will make your code even shorter:
$name = $db->getOne("SELECT name FROM users WHERE job=?s",$job);
if ($name) {
echo $name;
} else {
echo "No results found dude";
}
But it would be wise to get yourself familiar with raw API functions first.
I'm trying to fetch results using mysqli->fetch_row() (or fetch_object(), fetch_array()), yet when I go to run the code at run time it gives me the following error:
Fatal error: Call to a member function fetch_row() on a non-object in...on line 23.
The var in question that does this is $results in the code below. $user and $password gain their values from another .php file that this file is being included in so that's not really important at the moment. Now correct me if I'm wrong but if $results is being set = to $db->query($query) then isn't it supposed to inherit the properties of $db aka the mysqli class?
class mySQLHelper{
public function checkPass($user, $pass){
global $db;
$db = new mysqli();
$db->connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()){
echo 'Can not connect to database';
echo mysqli_connect_errno(). mysqli_connect_error();
exit;
return false;
}
$query = "SELECT user, password FROM Users WHERE user = $user AND password = $pass " ;
echo $query;
$results = $db->query($query);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
$results->close();
$url = 'http://'. $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
if(!$results){
// mysqli_close($db);
// header("Location:.$url.login.php&msg=1");
}
else{
// mysqli_close($db);
// header("Location:.$url.featured.php");
}
}
}
Your query is failing on this line:
$results = $db->query($query);
Because of this, $results is false - not a result object as you expect.
To fix the issue, you need to add quotes around your variables (or use prepared statements):
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
I would suggest updating to use a prepared statement to prevent SQL-injection issues too though:
$stmt = $db->prepare('SELECT user, password FROM Users WHERE user = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$results = $stmt->get_result();
You script is lacking error checking, and therefore the error in the query is not handled.
$query = "SELECT user, password FROM Users
WHERE user = '$user' AND password = '$pass' " ;
// ^ quotes needed
echo $query;
$results = $db->query($query);
// handle a error in the query
if(!$results)
die($db->error);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
If you user & password field text or varchar, then you need to use single quote around them
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
You have to check, if query runs properly:
if ($result = $mysqli->query($query))
{
}
Use: var_dump($results) to check what it contains
Why are you checking if($results) after trying to manipulate it?
This...
$results->close();
//...
if(!$results){
//...
}
Should be...
if(!$results){
//...
}
$results->close();