mysql_real_escape_string, query and number of rows - php

include("lib/config.php");
include("lib/mysql.php");
if ($_GET['action'] == "loginsignup") {
$error = "";
if(!$_POST['email']) {
$error = "an email address is needed";
} else if(!$_POST['password']) {
$error = "a password is needed";
} else if (filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) === false) {
$error = "please enter a valid email address";
}
if ($error != "") {
echo $error;
exit();
}
if($_POST['loginactive'] == "0") {
$query = "SELECT * FROM 'users' WHERE email = '".mysql_real_escape_string($link, $_POST['email'])."' LIMIT 1 ";
$result = mysql_query($link,$query);
if(mysql_num_rows($result) == 0) $error = "that email address is already taken.";
}
if ($error != "") {
echo $error;
exit();
}
}
so here is the code im trying to verify if there are any errors and if there is an email in my database that has the same one thats being signed up so im getting these errors
mysql_real_escape_string() expects parameter 1 to be string, resource given
mysql_query() expects parameter 1 to be string, resource given in
mysql_num_rows() expects parameter 1 to be resource null given in
and i really i tried going back and forth with mysqli and mysql and they both have the same errors

You're passing as argument a variable which is either declared or initialized to mysql_real_escape_string(), which is causing it to return an unexpected result, causing mysql_query() & mysql_num_rows() not receiving the expected parameters.
Hope it helps!

Related

Login count in php

I have a login script I want if user attempt 3 invalid password then the username associated to them would be disabled or blocked for a day / 24hrs.
Since I make a if condition in php login code where status=3 alert your account is blocked for a day.
status is my database column name which count the value of invalid login of user from 1 to 3 maximum.
But issue is my here that is how I make the status automatically count or increase like 1, 2, 3 in user invalid login.
How to I add this function with my login code
I have not idea about that. On YouTube there is not any video regards this even in other website.
Stackoverflow is my last hope where someone helps user.
Please have a look at this question and help to create satatus count automatic when user inter invalid password.
My login PHP is : https://pastebin.com/QpwDtjBg
Thank you in advance
You're gonna want to use PHP's $_SESSION object.
In the code block where you detect bad user/pass combos, add an iterator to the session.
First, add a session entry to the top of your script (Or wherever you define global variables), for bad_logins, and start your session.
session_start();
$_SESSION['bad_logins'] = 0;
Then in the part of your code where you detect a bad login, increment the bad logins by 1.
$_SESSION['bad_logins']++;
This will allow you to then check for bad attempts with an if statement
if($_SESSION['bad_logins'] > 3) {
// Do something here.
}
The script you linked has some other issues you may want to address prior to adding this in though.
You just need to add an update to the field 'status' on the database with 1, 2 or 3, on the IF condition:
if($data == NULL || password_verify($password, $data['Password']) == false) {
And read that same field, when the submit form is sent every single time... if it is already 3, then just skip to the IF condition
if($data['Status'] == "//auto count//")
Something like this (haven't tested the code) and the code should be function based, at least...
`
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if(isset($_POST['submit'])) {
$messages = array(
'INVALID_EMAIL' => "<div class='alert-box warning error'><span>Invalid format, re-enter valid email.</span></div>",
'ALL_FIELDS_REQUIRED' => "All field is mandatory! case sensitive.",
'VERIFY_EMAIL' => "Please verify your email!",
'INVALID_COMBINATION' => "Invalid username or password combinations.",
'BLOCKED' => "you are blocked for a day. <a href='#'><span>Know why?<span></a>",
);
$msg = "";
$error = false;
$con = new mysqli("localhost", "softwebs_softweb", "test#123", "softwebs_cms");
$email = $con->real_escape_string(htmlspecialchars($_POST['username']));
$password = $con->real_escape_string(htmlspecialchars($_POST['password']));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$msg = $messages['INVALID_EMAIL'];
$error = true;
}
if ($email == "" || $password == "") {
$msg = $messages['ALL_FIELDS_REQUIRED'];
$error = true;
}
if(!$error) {
$sql = $con->query("SELECT * FROM users where Email_ID = '$email' ");
if ($sql->num_rows > 0) {
$data = $sql->fetch_array();
// Blocked
if ($date['status'] === 3) {
$msg = $messages['BLOCKED'];
$error = true;
}
if ($data['isEmailConfirm'] == "0") {
$msg = $messages['VERIFY_EMAIL'];
$error = true;
}
if ($data == NULL || password_verify($password, $data['Password']) == false) {
$msg = $messages['INVALID_COMBINATION'];
$error = true;
// Update the status + 1
$sql = $con->query("UPDATE users SET status = " . $statusData['status'] + 1 . " WHERE Email_ID = '$email' ");
}
}
}
if($error && trim($msg) !== "") {
$msg = "<div class='alert-box error'><span>$msg</span></div>";
} else {
session_start();
$_SESSION['login']=$_POST['username'];
$_SESSION['id']=$data['id'];
header('location: ./account/dashboard.php');
}
}
?>
`

trying to convert mysql select statement to PDO

I'm trying to convert from an old MySQL library to PDO.
In order to read the data with my old MySQL code I use:
$assoc = mysql_fetch_assoc($exeqr);
With PDO I'm trying to do that with a foreach like I have on my code using PDO, but its not working...
Can you see something wrong here??
My OLD ode using MySQL:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['password']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$query = "SELECT * FROM users where email= '$autEmail'";
$exeqr = mysql_query($query) or die(mysql_error());
$assoc = mysql_fetch_assoc($exeqr);
if(mysql_num_rows($exeqr) == 1 )
{
if($autEmail == $assoc['email'] && $autpass == $assoc['pass'])
{
$_SESSION['assoc'] = $assoc;
header('Location:'.$_SERVER['PHP_SELF']);
}
else
{
echo ' wrong password';
}
}
else
{
echo 'email does no exist';
}
}
}
And the new code I am trying to convert using PDO:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['password']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$searchEmail = $pdo->prepare("SELECT * FROM users where email=:email");
$searchEmail->bindValue(":email,$autEmail");
$searchEmail->execute;
$num_rows = $searchEmail->fetchColumn();
$result = $searchEmail->fetch(PDO::FETCH_OBJ);
if($num_rows == 1)
{
if($autEmail == $result['email'] && $autpass == $result['pass'])
{
$_SESSION['result'] = $result;
header('Location:'.$_SERVER['PHP_SELF']);
}
else
{
echo ' wrong password';
}
}
else
{
echo 'email does no exist';
}
}
}
Warning: PDOStatement::bindValue() expects at least 2 parameters, 1 given in $searchEmail->bindValue(":email,$autEmail");
You need to move your ", currently it's including the variable as well as the parameter name resulting in you not passing in the variable to bind to said parameter (which is why you are getting the error telling you you haven't passed in enough arguments).
$searchEmail = $pdo->prepare("SELECT * FROM users where email = :email");
$searchEmail->bindValue(":email", $autEmail);
Notice: Undefined property: PDOStatement::$execute in $searchEmail->execute;
You've forgotten the () brackets from execute(), so PHP is looking for the property of the PDO class called execute instead of the function call.
$searchEmail->execute();
(thanks Prix)
Edit
Your question is now about how to replace this:
$assoc = mysql_fetch_assoc($exeqr);
... with a PDO equivalent. In the manual, there is an example:
$assoc = $searchEmail->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
Note: fetchAll() is for fetching multiple results. If you're expecting only one result (which you might be, but you aren't limiting your query so it's feasible to return multiple results), you should just use fetch():
$assoc = $searchEmail->fetch(PDO::FETCH_ASSOC);

Why am I getting all these errors?

Sorry if this seems pretty dumb but simple but I can't seem to figure out why I am getting these errors:
Warning: mysql_result() expects parameter 1 to be resource, boolean given in C:\Program Files (x86)\EasyPHP-5.3.9\www\Image Upload\func\user.func.php on line 25
Notice: Undefined index: user_id in C:\Program Files (x86)\EasyPHP-5.3.9\www\Image Upload\register.php on line 37
Here is the code for each file
user.func.php:
function user_exists($email){
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = `$email`");
return (mysql_result($query, 0) == 1) ? true : false;
}
and here is register.php:
if (isset($_POST['register_email'], $_POST['register_name'], $_POST['register_password'])){
$register_email = $_POST['register_email'];
$register_name = $_POST['register_name'];
$register_password = $_POST['register_password'];
$errors = array();
if(empty($register_email) || empty($register_name) || empty($register_password)){
$errors[] = 'All fields must be filled out';
}
else{
if(filter_var($register_email, FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'Email address not valid';
}
if(strlen($register_email) > 255 || strlen($register_name) > 35 || strlen($register_password) > 35){
$errors[] = 'One or more fields contains too many characters';
}
if(user_exists($register_email) === true){
$errors[] = 'That email has already been registered to another user';
}
}
if(!empty($errors)){
foreach ($errors as $error){
echo $error, '<br />';
}
} else {
$register = user_register($register_email, $register_name, $register_password);
$SESSION['user_id'] = $register;
echo $_SESSION['user_id'];
}
}
Thanks for any help!
-TechGuy24
The query is failing .. it should be email = '$email' (instead of surrounding the second email with backticks).
Please also look up prepared statements and PDO.
mysql_query will return FALSE (a boolean) when it fails and the "resource" you are seeking when it succeeds.
You're using backticks "`" on a value, so your query is failing, use single quotes '
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email'");

Mysql num rows issue

I run this query to check if cat_name already exists it the mysql database... but it's show a warning messag.
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs......"
<?php
include("db.php");
if(isset($_POST['cat_name']))
{
$cat_name = mysql_real_escape_string(htmlentities(trim($_POST['cat_name'])));
$err = array();
$ch = mysql_query("SELECT cat_name FROM categories WHERE cat_name = '$cat_name' ");
$num = mysql_num_rows($ch);
if(empty($cat_name))
$err[] = "Category field empty";
elseif(is_numeric($cat_name))
$err[] = "Category name should be string, ex: category name";
elseif($num > 0)
$err[] = "Category name already exits, please choose another name";
else
{
if(strlen($cat_name) < 3)
$err[] = "Category name at least 3 or more
characters";
}
if(!empty($err))
{
foreach($err as $er)
{
echo "<font color=red>$er.</font>";
}
}
else
{
$sql_insert = mysql_query("INSERT INTO categoires VALUES('',
'$cat_name')");
if($sql_insert)
{
echo "Successfully inserted your category name";
}
else
{
echo "Something is wrong to add your cateogory name";
mysql_error();
}
}
}
?>
Any idea?
Your query is failing (and returning false). Check mysql_error or the mysql/php error logs.
From the docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
mysql_query() will also fail and return FALSE if the user does not
have permission to access the table(s) referenced by the query.
My best guess is that you have an error in your query.

php error for registering a user

Im getting this error in a basic register script:
Warning: mysql_result() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/func/user.func.php on line 23
The part of the register.php that's giving me the error is:
<?php
include('init.php'); // user.func.php is included in this file
include('template/header.php');
?>
<h3>Register</h3>
<?php
// Typical $_POST stuff here, down the line the next line is where the error happenes. Also, $register_email below is equal to $_POST['register_email'];
if(user_exists($register_email)) { ***THIS FUNCTION IS WHERE THE PROBLEM IS. THE ACTUAL FUNCTION IS DEFINED BELOW***
$errors[] = 'That email has already been registered';
}
The function from user.func.php that's giving me the error is:
function user_exists($email) {
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT COUNT(user_id) FROM users WHERE email = '$email'");
return (mysql_result($query, 0) == 1) ? true : false; // ***THIS LINE RIGHT HERE***
}
Any ideas on what might be causing this error. It's an annoying error. Not the first time I've gotten that one.
UPDATE
Thanks for the answers, I've tried each one and I'm getting the exact same error. Here's the full register.php so far:
<?php
include('init.php');
include('template/header.php');
?>
<h3>Register</h3>
<?php
if(isset($_POST['register_email'], $_POST['register_name'], $_POST['register_password'])) {
$register_email = $_POST['register_email'];
$register_name = $_POST['register_name'];
$register_password = $_POST['register_password'];
$errors = array();
if(empty($register_email) || empty($register_name) || empty($register_password)) {
$errors[] = 'All fields required';
} else {
echo 'OK';
}
if(filter_var($register_email, FILTER_VALIDATE_EMAIL) == false) {
$errors[] = 'Email address is not valid';
}
if(strlen($register_email) > 255 || strlen($register_name) > 35 || strlen($register_password) > 35) {
$errors[] = 'Ayo, quit tampering with the html';
}
if(user_exists($register_email)) {
$errors[] = 'That email has already been registered';
}
}
if(!empty($errors)) {
foreach($errors as $error) {
echo $error.'<br />';
}
} else {
}
?>
Now, I must say first that I'm not a mysql specialist and I normally use a DB class (so should you.) But if you are saying that return (mysql_result($query, 0) == 1) ? true : false; line is giving you an error. It means that the line above is not working. Meaning that it is not returning a resource.
You should first debug your function..
function user_exists ($email) {
$email = mysql_real_escape_string($email);
if (!mysql_select_db("users")) {
echo 'Could not select "users" DB.<br />Error: ' . mysql_error();
}
$query = mysql_query("SELECT COUNT(user_id) AS `count` FROM `users` WHERE `email` = '$email'");
echo 'The count is currently: '$query['count'];
// return (mysql_result($query, 0) == 1) ? true : false;
}
If it says that it couldn't select the users DB. Then the problem is in your connections. As I said, I'm no pro. But you should probably connect it like this:
$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
Now you can try this:
function user_exists ($email) {
global $conn;
$email = mysql_real_escape_string($email);
if (!mysql_ping($conn)) {
echo 'Could not ping the mysql. Connection is lost probably :(';
}
$query = mysql_query("SELECT COUNT(user_id) AS `count` FROM `users` WHERE `email` = '$email'", $conn);
echo 'The count is currently: ' . mysql_result($query, 0);
// return (mysql_result($query, 0) == 1) ? true : false;
}
If the code is been debugged and connection is AWESOME! Then:
function user_exists ($email) {
global $conn;
if ($email) {
$query = mysql_query("SELECT COUNT(user_id) AS `count` FROM `users` WHERE `email` = '$email'", $conn);
if (mysql_result($query, 0)) {
return true;
}
}
return false;
}
Or:
function user_exists ($email) {
global $conn;
if ($email) {
$query = mysql_query("SELECT COUNT(user_id) AS `count` FROM `users` WHERE `email` = '$email'", $conn);
if ($result = mysql_fetch_array($query)) {
if ($result['count'] == 0) {
return true;
}
}
}
return false;
}
If you look in the manual, mysql_query() can return a ressource (thats what you expect) OR FALSE if an error occur.
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
Change to:
function user_exists($email) {
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT email FROM users WHERE email = '$email'");
if (false === $query) return false;
return (mysql_num_rows($query) == 1);
}
use
function user_exists($email) {
if(isset($email){
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT COUNT(user_id) FROM users WHERE email = '$email'");
$result = mysql_result($query,0);
if($result ===false) {
//error occur with the sql statement
//handel the error
}
else
return ($result == 1) ? true : false; // ***THIS LINE RIGHT HERE***
}
}
function user_exists($email) {
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT COUNT(user_id) FROM users WHERE email = '$email'");
//return (mysql_result($query, 0) == 1) ? true : false; // ***THIS LINE RIGHT HERE***
if( $query ) return ( mysql_result($query, 0) != "" ) ? true : false;
}

Categories