trying to convert mysql select statement to PDO - php

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);

Related

Problem with 2 database queries and fetching data from row

Having a problem with the 2nd query. when it gets to mysql_fetch_row - it kicks back
mysqli_fetch_row() expects parameter 1 to be resource, boolean given
Now I have also tried fetch assoc. But that as well kicks back an error. I have tried doing the 2nd query with '$id' and without it, yet still nothing. I think i am missing something very obvious.
I have went through many of the common post on here that refer to the error I am given but still haven't found a solution.
$con1 = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$con2 = mysqli_connect($dbhost,$dbuser2,$dbpass2,$dbname2);
// Check connections
if($con1)
{ echo("1st Connection Successful "); }
else
{ echo("1st Connection Failed "); }
if($con2)
{ echo("2nd Connection Successful "); }
else
{ echo("2nd Connection Failed "); }
//start first database query
$query = "SELECT id, email FROM ow_base_user ORDER by ID LIMIT 30";
$result = $con1->query($query);
while($row = $result->fetch_row()) {
$rows[]=$row;
$id = $row[0];
$email_row = $row[1];
$email_sub = substr($email_row, 0, 2);
if ( $email_sub == "dk" ) {
$email = "1"; }
elseif ( $email_sub == "sv" ) {
$email = "3"; }
elseif ( $email_sub == "no" ) {
$email = "4"; }
elseif ( $email_sub == "nl" ) {
$email = "5"; }
elseif ( $email_sub == "de" ) {
$email = "2"; }
elseif ( $email_sub == "fi" ) {
$email = "6"; }
else {}
if (isset($email)) {
//start 2nd database query
$query2 = "SELECT country_id FROM website_user WHERE userId = $id LIMIT 1";
$result2 = $con2->query($query2);
$row2 = mysqli_fetch_row($result2);
$country = $row2[6];
if (isset($country)) {
}
if (DEVMODE) {
echo "user id = ".$id." -- ";
echo "email = ".$email." -- ";
echo "COUNTRY = ".$country."<br />";
}
}
}
So changed the code around a bit to print out errors incase the query wasn't going through.
If($result2 === false) {
echo "error while executing mysql: " . mysqli_error($con2);
} else {
after adding this in I received the error.
mysqli_error() expects parameter 1 to be mysqli, null given
Ok so, these errors where caused by a typo in the databse table name thanks for pointing out the error report all method in the comments.
UPDATE: so after fixing the connection issue. I receive Notice: Undefined offset: 5 in $country = $row2[6];
UPDATE: after change $country = $row2[0]; - This solved the final issue.
for development build you can use
error_reporting(E_ALL);
ini_set('display_errors', 1);
which showed the database table was misspelled. after that, had to change the which row was being pulled since it was only 1 row, instead of all rows.

PHP weird scope error, empty variable

Hello i have a weird scope problem
require 'connect.php';
$name = $_GET['R'];
echo $name;
if(isset($_POST['prev_password']) && isset($_POST['new_password']) && isset($_POST['rep_password'])) {
echo $name;
if(!empty($_POST['prev_password']) && !empty($_POST['new_password']) && !empty($_POST['rep_password'])) {
$user_password = $_POST['prev_password'];
$user_new_password = $_POST['new_password'];
$user_rep_password = $_POST['rep_password'];
if($user_new_password == $user_rep_password) {
$mysql_query = sprintf("SELECT username, password FROM users WHERE username='$name'", $name);
$query_run = mysql_query($mysql_query, $mysql_link) or die('COULD NOT PERFORM QUERY');
while($row = mysql_fetch_array($query_run)) {
$qUser_name = $row['username'];
$qUser_pass = $row['password'];
}
if($qUser_name == $name) {
echo 'Match';
if($qUser_pass == $user_password) {
$mysql_query = sprintf("UPDATE users SET password='$user_new_password' WHERE username='$name'", $name);
$query_run = mysql_query($mysql_query, $mysql_link) or die('COULD NOT PERFORM QUERY');
echo header('Location: main.php?C=1');
}else {
header('Location: main.php?C=4');
}
}
}else {
header('Location: main.php?C=3');
}
}else {
header('Location: main.php?C=2');
}
}
anyway, the problem is with the first variable $name, when i 'echo' $name its ok, displays the content correctly, but inside the (if sss) ITS EMPTY, idk why, i've tried using global, the GLOBALS array, and its still empty, ... so .. the query its executed with an empty parameter.
please help, if someone can see what could be possible wrong.
PD: this is a Changepassword.php the $_GET['R'] is getting from the user Main.php site, AND I KNOW, im not Hashing password,, that is not really the problem here

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'");

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;
}

problem in a validation form - php

i have a problem in my code. I have an ajax validation that calls a php file (where the data is validated).
The php returns echos like "invalidData" and in the javascript i check if (data=="invalidData") {//something}
The problem are the includes. Incredible thing.
<?php
include("includes/f_banco.php");
conecta ();
function get_post_var($var) {
$val = $_POST[$var];
if (get_magic_quotes_gpc())
$val = stripslashes($val);
return $val;
}
$name = get_post_var('name');
function validateName($name){
if(strlen($name) < 4 || (empty($name))) {
echo "invalidData";
return false;
}
else {
$name = mysql_real_escape_string($name);
$check = mysql_query("SELECT username FROM users WHERE username ='".$name."'")
or die(mysql_error());
$check2 = mysql_num_rows($check);
if ($check2 == 0 && $name != "") {
echo "validData";
return true;
} else {
echo "invalidData";
return false;
}
}
}
error_reporting(E_ALL);
validateName($name);
?>
in the code above i only can check if the name is empty if i don't put the includes in the file. If i put the result is again and again different than invalidData.
The connection to the database is not made too or if is made the return is not the correct. Important: the include file is correct, i test in another example and the database is correct too.
thanks
Edit: **LAST VERSION**
<?php
error_reporting(-1);
require 'includes/f_banco1.php';
$name = $_POST["carlos"];
function validateName($name){
if(strlen($name) < 4 || (empty($name))) {
echo "nomeInvalido";
return false;
}
else {
$name = mysql_real_escape_string($name);
$check = mysql_query("SELECT username FROM users WHERE username ='".$name."'")
or die(mysql_error());
$check2 = mysql_num_rows($check);
if ($check2 == 0 && $name != "") {
echo "nomeValido";
return true;
} else {
echo "nomeInvalido";
return false;
}
}
}
validateName($name);
echo "this must appear";
?>
output:
Notice: Undefined index: carlos in C:\Users\fel\VertrigoServ\www\login\validation.php on line 8
nomeInvalidothis must appear
Probably PHP debug 101... just do a
<?php
error_reporting(-1);
...
?>
And inspect the error...
Try updating your query to be the following:
SELECT `username` FROM users WHERE `username` ='".$name."'
And, another question... If you already know what the username is, then why are you running a query to find the username? I assume you're just checking to see if the username exists.

Categories