Why am I getting Error: Query was empty? - php

I am creating a login part to my web page. When a new person registers their details, pressing the register button goes to a register_ok part, showing below:
case 'register_ok':
if (!$_POST['client_username'] || !$_POST['client_password'] ||
!$_POST['client_email']) {
die('You did not fill in a required field.');
}
// check if username exists in database.
if (!get_magic_quotes_gpc()) {
$_POST['client_username'] = addslashes($_POST['client_username']);
}
$qry = "SELECT client_username FROM client WHERE client_username = '".$_POST['client_username']."'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
die('Sorry, the username: <strong>'.$_POST['client_username'].'</strong>'
. ' is already taken, please pick another one.');
}
}
// check e-mail format
if (!preg_match("/.*#.*..*/", $_POST['client_email']) ||
preg_match("/(<|>)/", $_POST['client_email'])) {
die('Invalid e-mail address.');
}
// no HTML tags in username, website, location, password
$_POST['client_username'] = strip_tags($_POST['client_username']);
$_POST['client_password'] = strip_tags($_POST['client_password']);
// now we can add them to the database.
// encrypt password
$_POST['client_password'] = md5($_POST['client_password']);
if (!get_magic_quotes_gpc()) {
$_POST['client_password'] = addslashes($_POST['client_password']);
$_POST['client_email'] = addslashes($_POST['client_email']);
}
$insert = "INSERT INTO client (
client_username,
client_password,
client_name,
client_email,
client_last_access)
VALUES (
'".$_POST['client_username']."',
'".$_POST['client_password']."',
'".$_POST['client_name']."',
'".$_POST['client_email']."',
'now()'
)";
if(!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
else{
$id= mysql_insert_id();
session_start();
echo '<script>alert("You May Now Login");</script>';
echo '<meta http-equiv="Refresh" content="0;URL=pv.php">';
}
break;
}
When I register a new person, I get the following error:
Error: Query was empty
Why is this?

In the line if(!mysql_query($sql,$con)) {, do you mean $insert instead of $sql?

Do:
if(!mysql_query($sql,$con)) {
to
if(!mysql_query($insert,$con)) {
your variable name is not correct

Related

I want to implement something that doesn't allow the user to rate more than once

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.

Trying to get property of non-object - PHP

So I'm trying to get the teacher_id that is corresponding to the teacher's first and last name that the user has entered, but when I try to get the teacher_id it outputs Trying to get property of non-object. Does anyone have any ideas?
PHP
<?php
// PROCESSES STUDENT INFO
// get connect page
require '../../connect.php';
// get input info
$student_id = $_POST['student_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$teacher_first_name = $_POST['teacher_first_name'];
$teacher_last_name = $_POST['teacher_last_name'];
// check if input is not empy
if(!empty($student_id) && !empty($first_name) && !empty($last_name) && !empty($teacher_first_name) && !empty($teacher_last_name)) {
// check if numeric inputs have a number
if(is_numeric($student_id)) {
$teacher_check = mysqli_query($link, "SELECT teacher_id FROM teachers WHERE first_name='$teacher_first_name' AND last_name='$teacher_last_name'");
// check if teacher exists
if($teacher_check) {
$row = $teacher_check->fetch_object();
$result = mysqli_query($link, "INSERT INTO students (student_id, first_name, last_name, teacher_id) VALUES ($student_id, '$first_name','$last_name', $row->teacher_id)");
if($result) {
header("Location: ../../../admin.php?message=Success!");
} else {
echo mysqli_error($link);
// header("Location: ../../../admin.php?message=Sorry we ran into an error");
}
} else {
header("Location: ../../../admin.php?message=Teacher Does Not Exist");
}
} else {
header("Location: ../../../admin.php?message=Please add a number for Student ID");
}
} else if (empty($student_id) || empty($first_name) || empty($last_name)) {
header("Location: ../../../admin.php?message=Please add you're input values");
}
?>
change this line, you are checking whether the query is ok but you have not checked whether it has any results.
if($teacher_check) {
$row = $teacher_check->fetch_object();
to (this line checks whether you have any result data if you have result data you have it $row otherwise null)
if($row = $teacher_check->fetch_object()){

Php login script with login attemp

How can i limit the failed logins with this script? If the login fails, i insert it into the sql. (Is it the right way?)
But how can i check at the next login, that the user can now log in? I would take the login limit in 1 hour.
Aniway, is this code is good for that?
<?php
$loginError = array();
if(isset($_POST['login_submit']))
{
if(empty($_POST['email']) or !isset($_POST['email'])){$loginError[] = "Hiányzó email cím.";}
if(empty($_POST['pass']) or !isset($_POST['pass'])){$loginError[] = "Hiányzó jelszó.";}
if(strlen($_POST['email']) > 50 ){$loginError[] = "Hibás adat az email mezőben.";}
if(strlen($_POST['pass']) > 40 ){$loginError[] = "Hibás adat a jelszó mezőben.";}
if(count($loginError) == 0 )
{
$email = mysqli_real_escape_string($kapcs,$_POST['email']);
$pass = sha1($_POST['pass']);
$lekerdezes = mysqli_query($kapcs, "SELECT * FROM admin_user WHERE email = '$email'") or die(mysqli_error($kapcs));
if(mysqli_num_rows($lekerdezes) > 0 )
{
$adat = mysqli_fetch_assoc($lekerdezes);
if($adat['status'] == 1 )
{
if($adat['pass'] == $pass)
{
$_SESSION['adatok'] = $adat;
$_SESSION['email'] = $adat['email'];
$_SESSION['userid'] = $adat['id'];
header("Location:home.php");
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Még nincs aktiválva a fiók.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
}
?>
I would create a field in the database called status (blocked/ok) and assuming youve got a field timestamp for the last login...
Then Id connect to the database in case the login fails and save the status bloqued and the time stamp. the next attempt you would check the time.now vs last access...
I good suggestion would be create a function for the database connection so you can call it a couple of time without repeat the code, also dont forget use the try/except fot the db connection.

Query Checking for Existence - PHP

I'm trying to to test to see if an email address exists in my database by running a query check.
I can connect to the database fine.
However no matter what, even if the email exists it returns "doesn't exist".
<?php
//----------------------------------------------------------------------------------//
//Setup
require_once('SB_Constants.php');
//----------------------------------------------------------------------------------//
//Connect to the database
//----------------------------------------------------------------------------------//
$connection = mysqli_connect(DATABASE_HOST, SAVE_USERNAME, SAVE_PASSWORD, DATABASE_NAME);
// check the connection was successful
if (mysqli_connect_errno($connection)) {
header('HTTP/1.0 500 Internal Server Error', true, 500);
die(FailedToAccessDatabase . ". Failed to connect to Database");
} else {
echo "Connection Success!";
}
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT email_address FROM assessorID WHERE email_address = 'ryan#ablah.com'");
if (mysqli_num_rows($query_identifier) == 0) {
die(UnregisteredAssessor . ". Doesn't Exist");
} else {
// Exists
echo "Exists getting ace id.";
//Get the assessor ID
$result = mysqli_query($connection, "SELECT ace_id FROM assessorID WHERE email_address = 'ryan#blah.com'");
echo $result;
}
/* close connection */
mysqli_close($connection);
?>
Any ideas of the problem? :)
Various mistakes. Fix:
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = 'ryan#ablah.com'");
if (mysqli_num_rows($assessorEmail) == 0) {
die(UnregisteredAssessor . ". Doesn't Exist");
} else {
// Exists
echo "Exists getting ace id.";
//Get the assessor ID
$result = mysqli_fetch_assoc($assessorEmail);
echo $result['ace_id'];
}
Your problem is mysqli_num_rows($query_identifier) is accessing an undefined variable instead of $assessorEmail.
Additionally, you only need one query if you just want the ace_id:
$assessorEmail = mysqli_query($connection, "SELECT ace_id FROM assessorID WHERE email_address = 'ryan#ablah.com'");
If mysqli_num_rows($assessorEmail) returns a row, than the email exists and you already have the ace_id
while(mysqli_fetch_assoc($assessorEmail) = $row) {
echo $result['ace_id'];
}

Error with login processing system

I have created a login system for my webpage, but when I enter in the username and password, it fails to get past the first stage of the process. Anyone have any ideas on what the problem maybe, I have provided the code below.
if(!$_POST['client_username'] || !$_POST['client_password']) {
die('You did not fill in a required field.');
}
if (!get_magic_quotes_gpc()) {
$_POST['client_username'] = addslashes($_POST['client_username']);
}
$qry = "SELECT client_username, client_password FROM client WHERE client_username = '".$_POST['client_username']."'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) == 1) {
die('That username does not exist in our database.');
}
}
// check passwords match
$_POST['client_password'] = stripslashes($_POST['client_password']);
$info['client_password'] = stripslashes($info['client_password']);
$_POST['client_password'] = md5($_POST['client_password']);
if ($_POST['client_password'] != $info['client_password']) {
die('Incorrect password, please try again.');
}
// if we get here username and password are correct,
//register session variables and set last login time.
$client_last_access = 'now()';
$qry = "UPDATE client SET client_last_access = '$client_last_access' WHERE client_username = '".$_POST['client_username']."'";
if(!mysql_query($insert,$con)) {
die('Error: ' . mysql_error());
}
else{
$_POST['client_username'] = stripslashes($_POST['client_username']);
$_SESSION['client_username'] = $_POST['client_username'];
$_SESSION['client_password'] = $_POST['client_password'];
echo '<script>alert("Welcome Back");</script>';
echo '<meta http-equiv="Refresh" content="0;URL=pv.php">';
}
When I fill in the username and password, it dies at the first stage and shows the message:
You did not fill in a required field.
You should use || instead of a simple |.
I'm in a good mood.
Here's your code. It should work.
<?php
if( empty( $_POST['client_username'] ) || empty( $_POST['client_password'] ) ) {
die('You did not fill in a required field.');
}
$qry = sprintf( "SELECT client_username, client_password FROM client WHERE client_username = '%s' LIMIT 1", mysql_real_escape_string( $_POST['client_username'] ) );
$result = mysql_query( $qry );
if( $result ) {
if( mysql_num_rows( $result ) == 0 ) {
die('That username does not exist in our database.');
}
}
// where the f**k do you get your info? i added some.
$info = mysql_fetch_assoc( $result );
if( md5( $_POST['client_password'] ) != $info['client_password'] ) {
die('Incorrect password, please try again.');
}
// if we get here username and password are correct,
//register session variables and set last login time.
$qry = sprintf( "UPDATE client SET client_last_access = NOW() WHERE client_username = '%s'", $info['client_username'] );
if( !mysql_query( $qry ) ) {
die('Error: ' . mysql_error() );
} else {
$_SESSION['client_username'] = $info['client_username'];
$_SESSION['client_password'] = $info['client_password'];
echo '<script>alert("Welcome Back");</script>';
echo '<meta http-equiv="Refresh" content="0;URL=pv.php">';
}
Your login code contains serious flaws which lead to security issues. In short: magic_quotes compatibility and SQL injection. I don't cover them. Your problem you highlight in your question is the one | when you meant || in the first stages if clause:
if (!$_POST['client_username'] || !$_POST['client_password'])
^^
See Logical Operators Docs. You've used a Bitwise Operator Docs.

Categories