$dbh->query works on $queryUser = $dbh->query, but not on $querySessions = $dbh->query, $querySessions is null,
echo $querySessions == null; echos 1
and then
Fatal error: Call to a member function fetchAll() on a non-object in
/path/to/file.php on line (while(count($querySessions->fetchAll()) !=
0))
if($_POST['loginbtn'])
{
$User = $_POST['user'];
$Pass = md5(md5("salt" . $_POST['pass'] . "salt2"));
if($User)
{
if($_POST['pass'])//not $Pass because thats hashed
{
$queryUser = $dbh->query("SELECT * FROM `Users` WHERE `UserName` = '" . base64_encode($User) . "' LIMIT 1");
$Record = $queryUser->fetch();
if($Pass != $Record["Password"])
{
echo "Incorect password.";
}
else
{
if($Record["Banned"] == 1)
{
echo "Sorry, your banned.";
}
else
{
if($Record["NeedsActivation"] == 1)
{
echo "You must activate your account before you can login.";
}
else
{
$SID = md5(rand(0,0x7fffffff) . "salt3");
$querySessions = $dbh->query("SELECT * FROM `Sessions` WHERE `ID` = " . $SID . " LIMIT 1");
echo $querySessions == null;
while(count($querySessions->fetchAll()) != 0)
{
$SID = md5(rand(0,0x7fffffff) . "salt2");
$querySessions = $dbh->query("SELECT * FROM `Sessions` WHERE `ID` = " . $SID . " LIMIT 1");
}
$_SESSION['id'] = $SID;
$dbh->query("INSERT INTO `godzchea_Site`.`Sessions` (`ID` ,`UserID`)VALUES ('" . $SID . "', '" . $Record["ID"] . "');");
echo base64_decode($Record["UserName"]) . " Logged in.";
}
}
}
}
else
{
echo "You must enter your password.";
}
}
else
{
echo "You must enter your username.";
}
}
can any of you see why its being set to null,
and if there's a better way to loop till I get a empty id.
The problem stand in the fact that that query, the one associated to $querySession is being a failure. Probably there's an error in your query because what the Manual say is:
PDO::query() returns a PDOStatement object, or FALSE on failure.
I'm not sure, but it also could be that no rows has been found.
A suggestion I could give to you, to find out what's the real errors is:
You put all of your PDO code inside a try catch block like: try{/*code in here*/}catch(PDOException $e){ exit($e->getMessage()); } and see what it output.
Take the query and the value of $SID and try to run it into phpmyadmin, directly into the database.
Note that the fatal error is also related to the fact that your query is returning false instead of an object. That errors just say that you are treating $querySession as an object but it is not.
For more information just leave a comment and I'll answer.
Good luck.
Related
I have used someone else's code that uses the ipaddress way. However, I would like to use a code that checks for the current userid and the id number.
$ipaddress = md5($_SERVER['REMOTE_ADDR']); // here I am taking IP as UniqueID but you can have user_id from Database or SESSION
/* Database connection settings */
$con = mysqli_connect('localhost','root','','database');
if (mysqli_connect_errno()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
} /* end of the connection */
if (isset($_POST['rate']) && !empty($_POST['rate'])) {
$rate = mysqli_real_escape_string($con, $_POST['rate']);
// check if user has already rated
$sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $ipaddress . "'";
$result = mysqli_query( $con, $sql);
$row = mysqli_fetch_assoc();//$result->fetch_assoc();
if (mysqli_num_rows($result) > 0) {
//$result->num_rows > 0) {
echo $row['id'];
} else {
$sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $ipaddress . "'); ";
if (mysqli_query($con, $sql)) {
echo "0";
}
}
}
//$conn->close();
In your database table, set the user_id column as UNIQUE KEY. That way, if a user tries to cast a second vote, then the database will deny the INSERT query and you can just display a message when affected rows = 0.
Alternatively, (and better from a UX perspective) you can preemptively do a SELECT query for the logged in user before loading the page content:
$allow_rating = "false"; // default value
if (!$conn = new mysqli("localhost", "root","","database")) {
echo "Database Connection Error: " , $conn->connect_error; // never show to public
} elseif (!$stmt = $conn->prepare("SELECT rate FROM tbl_rating WHERE user_id=? LIMIT 1")) {
echo "Prepare Syntax Error: " , $conn->error; // never show to public
} else {
if (!$stmt->bind_param("s", $ipaddress) || !$stmt->execute() || !$stmt->store_result()) {
echo "Statement Error: " , $stmt->error; // never show to public
} elseif (!$stmt->num_rows) {
$allow_rating = "true"; // only when everything works and user hasn't voted yet
}
$stmt->close();
}
echo "Rating Permission: $allow_rating";
And if they already have a row in the table, then don't even give them the chance to submit again.
I'm just learning PHP and I thought it would be a good idea to learn some MySQL too.So I started working on the code and for some strange reason I keep getting duplicate users which is really really bad.
<?php
$link = mysqli_connect(here i put the data);
if(!$link)
{
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else
{
if(isset($_POST['user']))
{ echo "User set! "; }
else { echo "User not set!"; exit; }
if(isset($_POST['pass']) && !empty($_POST['pass']))
{ echo "Password set! "; }
else { echo "Password not set!"; exit; }
$num = mysqli_num_rows(mysqli_query("SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
if($num > 0)
{ echo "Cannot add duplicate user!"; }
mysqli_close($link);
}
?>
For some strange reason I don't get the output I should get.I've tried some solutions found here on StackOverflow but they didn't work.
The first parameter of connectionObject is not given in mysqli_query:
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( `username` = '".$_POST['user']."' )"));
//----------------------------------^^^^^^^
Also, your code is vulnerable to SQL Injection. A simple fix would be:
$_POST['user'] = mysqli_real_escape_string($link, $_POST['user']);
mysqli_query must receive two parameters in order to work. In this case, your mysqli_connect.
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
Also, you can be affected by SQL Injection, in this code.
Never add user input directly in your queries without filtering them.
Do that to make your query more readable and safe:
$u_name=mysqli_real_escape_string($link, $_POST['user']);
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = '$u_name' )"));
To use mysqli_* extension, you must include your connection inside of the parameters of all queries.
$query = mysqli_query($link, ...); // notice using the "link" variable before calling the query
$num = mysqli_num_rows($query);
Alternatively, what you could do is create a query() function within your website, like so:
$link = mysqli_connect(...);
function query($sql){
return mysqli_query($link, $sql);
}
and then call it like so:
query("SELECT * FROM...");
This could be a problem of race condition.
Imagine that two users wants to create the same username at the same time.
Two processes will execute your script. So both scripts select from database and find out that there is not an user with required username. Then, both insert the username.
Best solution is to create unique index on username column in the database.
ALTER TABLE users ADD unique index username_uix (username);
Then try insert the user and if it fails, you know the username exists ...
Here's how to write your code using prepared statements and error checking.
Also uses a SELECT COUNT(*)... to find the number of users instead of relying on mysqli_num_rows. That'll return less data from the database and just seems cleaner imo.
<?php
$link = mysqli_connect(here i put the data);
if(!$link) {
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else if(!isset($_POST['user'])) {
echo "User not set!"; exit;
}
echo "User set! ";
if(!isset($_POST['pass']) || empty($_POST['pass'])) {
echo "Password not set!"; exit;
}
echo "Password set! ";
$query = "SELECT COUNT(username)
FROM users
WHERE username = ?";
if (!($stmt = $mysqli->prepare($query))) {
echo "Prepare failed: (" . mysqli_errno($link) . ") " . mysqli_error($link);
mysqli_close($link);
exit;
}
$user = $_POST ['user'];
$pass = $_POST ['pass'];
if(!mysqli_stmt_bind_param($stmt, 's', $user)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
if (!mysqli_execute($stmt)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$num = $row[0];
if($num > 0) {
echo "Cannot add duplicate user!";
}
}
mysqli_stmt_close($stmt);
mysqli_close($link);
please do suggest fixes to syntax, this was typed from a phone
i have been trying since yesterday, and almost covered all questions regarding this matter in Stackoverflow plus googling, but so far nothing is working with me, i try to check username availability before updating the username in database, however, it wont check and always update the username directly without error message regarding not availability of the name..
here my code
//new connection
$con = new mysqli("localhost", "student", "student", "C14D5");
if ($con->connect_errno) { //failed
echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
//success
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['clientN'])) {
$query = mysqli_query("SELECT client_name FROM clients WHERE client_name='".$_POST['clientN']."'");
if (mysqli_num_rows($query) != 0) {
echo "<script>
alert('Username is not available, please select another username.');
</script>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
// run sql
$sql ="UPDATE `clients` SET `client_name` = '".$_POST['clientN']."' WHERE `client_ID` = '".$_POST['SelectClient']."'";
if ($con->query($sql) === TRUE) {
echo "<h3> New record created successfully</h3>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
echo "Error : " . $sql . "<br>" . $con->error;
}
$con->close();
}
}
You can use the mysqli_num_rows() function to avoid data duplication in your database
use this code :
//specify the database connection factors as usual ,then
$uname = $_POST['your_username_field'];
$sql = "SELECT * FROM your_db where username='$uname'";
//the variable 'sql' will store the resultset of the query
$num_row = mysqli_num_rows($sql);
// the 'num_row' will store the number of rows which matches your $sql resultset. So if it is greater than '0' then the data already exists
if( $num_row > 0)
{
// display 'username exists error'
}
else
{
// Insert user name into your database table
}
If the num_rows is greater than 0 ,then the username is already present in your database table . So at that case throw error. else INSERT the user name into your database and display success message .
<?php
if (intval($_GET['page']) == 0) {
redirect_to("staff.php");
}
$id = mysqli_prep($_GET['page']);
$query3 = "DELETE FROM page WHERE id = {$id}, LIMIT 1";
$result = mysqli_query($connection, $query3);
if (mysqli_affected_rows($connection) == 1) {
redirect_to("staff.php");
} else {
// Deletion Failed
echo $id ."<br />" . $query3 . "<br />" . $result . "<p>Subject
deletion failed.</p>";
echo "<p>" . mysqli_error() . "</p>";
echo "Return to Main Page";
}
// Keep on working Edit:2#
mysqli_query($connection, "DELETE FROM pages WHERE id = 11 ");
//- Works
Edit 3#
$id = $_GET['page'];
echo "<p>" . $id ."</p>";
$query3 ="DELETE FROM pages WHERE id = {$id} ";
mysqli_query($connection,$query3 );
// Still Works -- YaY for working backwards
// Edit #4 By "now it might be obvious what my error was "pages" not "page"
// Thanks everyone - And thank you for telling me about the error page
// My defense - newbie- Anyway Lesson from this - working backwards
// Takes a while, Error checking Fast!!!!!!
?>
$connection is started and selected. The $id is selected successfully, and the $page = $id, but it still will not work. $query 3 seems fine, but Deletion failed. I don't have any idea what the error is. Thanks for any help in advance.
-Josh Edit Check Error Check
You have a comma after the ID:
$query3 = "DELETE FROM page WHERE id = {$id}, LIMIT 1";
^ remove this
I don't have any idea what the error is.
That's because you didn't check. Every time you prepare or execute a query, you need to check for errors. Most of the functions in mysqli return FALSE if they encounter an error.
$result = mysqli_query($connection, $query3);
if ($result === false) {
trigger_error(mysqli_error($connection), E_USER_ERROR);
header("Location: /error.php");
exit;
}
The failure to check for error cases is one of the most common blunders committed by database programmers.
if ($page == get_page_by_id($id)) {
== for comparison
=== to compare the value and the cast
$val = true;
if ($val === true) {
echo "\$val is bool(true)";
}
if ($val == "true") {
echo "\$val matches value";
}
if ($val === "true") {
// this will never happen
} else {
echo "\$val doesnt === \"true\"";
}
try to use php_flag display_errors on in your .htaccess
this will allow you to see and identify php errors.
How do I check if username or email exists and then put a error message in my error array. Right now i have:
$sql = "SELECT username, email FROM users WHERE username = '" . $username . "' OR email = '" . $email . "'";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0)
{
echo "That username or email already exists";
}
But I want to check if it is the username OR the email that is existing and then put:
error[] = "username is existing"; //if the username is existing
error[] = "email is existing"; //if the email is existing
How to do?
It would be easier if you just did a quick true/false check in the SQL and checked the flag that came back.
$sql = "SELECT "
. "(SELECT 1 FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "'), "
. "(SELECT 1 FROM `users` WHERE `email` = '" . mysql_real_escape_string($email) . "')";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$foundFlags = mysql_fetch_assoc($query);
if ($foundFlags['username']) {
$error[] = "username is existing";
}
if ($foundFlags['email']) {
$error[] = "email is existing";
}
} else {
// General error as the query should always return
}
When it does not find an entry, it will return NULL in the flag, which evaluates to false, so the if condition is fine.
Note that you could generalise it for a field list like this:
$fieldMatch = array('username' => $username, 'email' => $email);
$sqlParts = array();
foreach ($fieldMatch as $cFieldName => $cFieldValue) {
$sqlParts[] = "(SELECT 1 FROM `users` WHERE `" . $cFieldName . "` = '" . mysql_real_escape_string($cFieldValue) . "')";
}
$sql = "SELECT " . implode(", ", $sqlParts);
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$foundFlags = mysql_fetch_assoc($query);
foreach ($foundFlags as $cFieldName => $cFlag) {
if ($foundFlags[$cFieldName]) {
$error[] = $cFieldName . " is existing";
}
}
} else {
// General error as the query should always return
}
NB. Note that assumes all fields are strings, or other string-escaped types (eg. date/time).
Sounds like you're trying to let users know whether a username or email already exists at registration time. Here's what you can do:
<?php
//----------------------------------------
// Create first query
$usernameQuery = 'SELECT username FROM users WHERE username="'.mysql_real_escape_string($username).'"';
//----------------------------------------
// Query db
$usernameResult = mysql_query($userNameQuery);
//----------------------------------------
// Check if result is empty
if(mysql_num_rows($usernameResult) > 0){
//----------------------------------------
// Username already exists
$error[] = 'Username already exists';
//----------------------------------------
// Return error to user and stop execution
// of additional queries/code
} else {
//----------------------------------------
// Check if email exists
//----------------------------------------
// Create query
$emailQuery = 'SELECT email FROM users WHERE email="'.mysql_real_escape_string($email).'"';
//----------------------------------------
// Query the db
$emailResult = mysql_query($emailQuery);
//----------------------------------------
// Check if the result is empty
if(mysql_num_rows($emailResult) > 0){
//----------------------------------------
// Email already exists
$error[] = 'Email already exists';
//----------------------------------------
// Return error to user and stop execution
// of additional queries/code
} else {
//----------------------------------------
// Continue with registration...
}
}
?>
Please note that you should always escape your values before executing the actual query.
Additional Resources:
http://us.php.net/manual/en/function.mysql-real-escape-string.php
http://us.php.net/manual/en/function.mysql-escape-string.php
You can fetch one row and see if you got same email that you search or same username or both. You can do LIMIT 0,1 if you can stop after finding first row matching either this or that.