What is wrong in these mysqli prepared statements? - php

I'm trying to make a registration script using PHP with Mysql database. The insertion cannot be done. If I register with an email-id which is already in the database, it is working fine. But, the script fails to insert new entries. It is returning 'bool(false)'.
I've tried the to do the same using PDO. The insertion can't be done. So, I tried mysqli prepared statements instead and even this yields the same result. Here is the code.
<?php
$dbh = new mysqli('localhost', 'user', 'pass', 'db');
if(isset($_POST['register'])){
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_POST['$name'];
$mail = $_POST['mail'];
$passw = $_POST['passw'];
$codeone = $_POST['codeone'];
$descs = $_POST['desc'];
$newstrings = 'specialstring';
$encrypted_pass = crypt( $passw );
$stmt = $dbh->prepare("SELECT mail FROM userrecs WHERE mail=?");
$stmt->bind_param('s',$mail);
if($stmt->execute())
{
$stmt->store_result();
$rows = $stmt->num_rows;
if($rows == 1)
{
session_start();
$_SESSION['notification_one'] = 'bla';
header('location:/someplace');
}
else {
$statement = $db->prepare("INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (?,?,?,?,?,?,?)");
$statement->bind_param('ssssiss',$ip,$name,$mail,$encrypted_pass,$codeone,$descs,$newstrings);
try {
if($statement->execute())
{
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
}
else
{
var_dump($statement->execute());
$statement->errorInfo();
}
}
catch(PDOException $pe) {
echo "S";
echo('Connection error, because: ' .$pe->getMessage());
}
}
}
}
else{
header('location:/someplace');
}
?>
EDIT:
This is the PDO-only code. I was mixing PDO and mysqli in the previous code.
<?php
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = 'user';
$password = 'pass';
$dbh = new PDO($dsn, $user, $password);
if(isset($_POST['regsubmit'])){
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_POST['$name'];
$mail = $_POST['mail'];
$pass = $_POST['passw'];
$codeone = $_POST['codeone'];
$descs = $_POST['desc'];
$newstrings = 'specialstring';
$encrypted_pass = crypt( $passw );
$sql = "SELECT mail FROM userrecs WHERE mail=:mail";
$statement = $dbh->prepare($sql);
$statement->bindValue(':mail',$mail,PDO::PARAM_STR);
if($statement->execute())
{
if($statement->rowCount() == 1)
{
session_start();
$_SESSION['noti_one'] = 'bla';
header('location:/someplace');
}
else {
$sql2 = "INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (:ip,:name,:mail,:encrypted_pass,:codeone,:descs,:newstrings)";
$stmt = $dbh->prepare($sql2);
$stmt->bindParam(':ip',$ip,PDO::PARAM_STR);
$stmt->bindParam(':name',$name,PDO::PARAM_STR);
$stmt->bindValue(':mail',$mail,PDO::PARAM_STR);
$stmt->bindParam(':encrypted_pass',$encrypted_pass,PDO::PARAM_STR);
$stmt->bindParam(':codeone',$codeone,PDO::PARAM_STR);
$stmt->bindParam(':descs',$descs,PDO::PARAM_STR);
$stmt->bindParam(':newstrings',$temstr,PDO::PARAM_STR);
try {
if($stmt->execute())
{
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
}
else
{
var_dump($stmt->execute());
$stmt->errorInfo();
}
}
catch(PDOException $pe) {
echo "S";
echo('Connection error, because: ' .$pe->getMessage());
}
}
}
}
else{
header('location:/someplace');
}
?>
Please ignore variable or table names. I edited some of the names here.

You are mixing PDO and mysqli driver in the same script, this is not possible.
Please use either one but not both.
PDO is the prefferred extension.
EDIT:
In your query:
INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (...)
NAME is a mysql reserved keyword, you escape it by using backticks:
INSERT INTO userrecs (ip,`name`,mail,pass,codeone_one,desc_one,spcstrings) VALUES (...)
EDIT:
Change
var_dump($statement->execute());
$statement->errorInfo();
to
var_dump($statement->errorInfo());
EDIT:
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = 'user';
$password = 'pass';
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['regsubmit'])) {
try {
$sql = "SELECT mail FROM userrecs WHERE mail=:mail";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':mail', $_POST['mail'], PDO::PARAM_STR);
if ($stmt->execute() && $stmt->rowCount() == 1) {
session_start();
$_SESSION['noti_one'] = 'bla';
header('location:/someplace');
} else {
$sql = "INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (:ip,:name,:mail,:encrypted_pass,:codeone,:descs,:newstrings)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
$stmt->bindValue(':name', $_POST['$name'], PDO::PARAM_STR);
$stmt->bindValue(':mail', $_POST['mail'], PDO::PARAM_STR);
$stmt->bindValue(':encrypted_pass', crypt($_POST['passw']), PDO::PARAM_STR);
$stmt->bindValue(':codeone', $_POST['codeone'], PDO::PARAM_STR);
$stmt->bindValue(':descs', $_POST['desc'], PDO::PARAM_STR);
$stmt->bindValue(':newstrings', 'specialstring', PDO::PARAM_STR);
if ($stmt->execute()) {
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
} else {
var_dump($stmt->errorInfo());
}
}
} catch (PDOException $pe) {
echo "S";
echo('Connection error, because: ' . $pe->getMessage());
}
} else {
header('location:/someplace');
}

I believe you have an error in your logic.
Try this code and see what you get ...
<?php
$dbh = new mysqli('localhost', 'user', 'pass', 'db');
if(isset($_POST['register'])) {
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_POST['$name'];
$mail = $_POST['mail'];
$passw = $_POST['passw'];
$codeone = $_POST['codeone'];
$descs = $_POST['desc'];
$newstrings = 'specialstring';
$encrypted_pass = crypt($passw);
$stmt = $dbh->prepare("SELECT mail FROM userrecs WHERE mail=?");
$stmt->bind_param('s', $mail);
$test = $stmt->execute();
if($test) {
$stmt->store_result();
$rows = $stmt->num_rows;
if($rows == 1) {
session_start();
$_SESSION['notification_one'] = 'bla';
header('location:/someplace');
} else {
$statement = $db->prepare("INSERT INTO userrecs (ip,name,mail,pass,codeone_one,desc_one,spcstrings) VALUES (?,?,?,?,?,?,?)");
$statement->bind_param('ssssiss', $ip, $name, $mail, $encrypted_pass, $codeone, $descs, $newstrings);
try {
if($statement->execute()) {
session_start();
$_SESSION['noti_two'] = 'bla';
header('location:/someplace');
} else {
var_dump($statement->execute());
$statement->errorInfo();
}
} catch (PDOException $pe) {
echo "S";
echo('Connection error, because: ' . $pe->getMessage());
}
}
}else{
echo "test is not ok";
var_dump($test);
}
} else {
header('location:/someplace');
}

Related

When opening the website, it says it cannot handle the request. Why?

I was hoping someone could help me figure why this code is not really working.
When i enter my website (with the GET), it says the server could not handle the request.
Could someone spot any errors?
I'm new to MySQL/MySQLi and PHP as well, so i'm sorry if any part of my code sounds pretty dumb.
Thanks in advance!!!
My table has the following organization:
-------------------
id | value
-------------------
|
|
-------------------
The column 'id' is an INT and the column 'value' is a JSON.
Here's my current code inside a script called "index.php".
<?php
$database = "...";
$username = "...";
$password = "...";
$servername = "localhost";
$mysqli = new mysqli($servername, $username, $password, $database);
if ($mysqli->connect_error) {
die("Connection failed: ".$mysqli->connect_error.".");
}
header("Content-type: application/json");
function get($id) {
if ($id) {
$query = "SELECT value FROM myTable WHERE id = ?";
$statement = $mysqli->prepare($query);
$statement->bind_param("i", $id);
$statement->execute();
$statement->bind_result($result);
$statement->fetch();
$statement->close();
if ($result) {
return $result;
}
else {
return NULL;
}
}
else {
return NULL;
}
}
function set($id, $value) {
if ($id && $value) {
$filled = get($id);
if ($filled) {
$query = "UPDATE myTable SET value = ? WHERE id = ?";
$statement = $mysqli->prepare($query);
$statement->bind_param("si", $value, $id);
$statement->execute();
$statement->bind_result($result);
$statement->fetch();
$statement->close();
if ($result) {
return TRUE;
}
else {
return FALSE;
}
}
else {
$query = "INSERT INTO myTable (id, value) VALUES (?, ?)";
$statement = $mysqli->prepare($query);
$statement->bind_param("is", $id, $value);
$statement->execute();
$statement->bind_result($result);
$statement->fetch();
$statement->close();
if ($result) {
return TRUE;
}
else {
return FALSE;
}
}
}
else {
return NULL;
}
}
$method = $_SERVER["REQUEST_METHOD"];
if ($method == "GET") {
$result = get($_GET["id"]);
echo $result;
}
elseif ($method == "POST") {
$result = set($_POST["id"], $_POST["value"]);
echo $result;
}
$mysqli->close();
?>

How to check if value in database is same with string in PHP

I want to find out not how to check if exsists, but to check is it same. Here's my code:
$user = $_COOKIE["c_user"];
$ip = $_SERVER['REMOTE_ADDR'];
$salt = $_COOKIE["c_salt"];
$chk_salt = mysql_fetch_array(mysql_query("SELECT * FROM `table1` WHERE `Salt`='$salt'"));
if ($chk_salt == '0') {
die("Get out!");
}
else {
echo "Welcome ".ucwords($user);
}
$host = 'your_mysql_host';
$dbname = 'your_db_name';
$user = 'username';
$pass = 'password';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage().'<br>';
}
$user = $_COOKIE["c_user"];
$ip = $_SERVER['REMOTE_ADDR'];
$salt = $_COOKIE ['c_salt'];
$chckSalt = $conn->prepare("SELECT * FROM table1 WHERE Salt=:salt");
$chckSalt->bindValue(':salt', $salt, PDO::PARAM_STR);
$chckSalt->execute ();
if ($chkSalt->rowCount () == 0) {
die("Get out!");
}
else {
echo "Welcome ".ucwords($user);
}

PHP Select with PDO Call to a member function prepare() on a non-object error

I'm getting a Call to a member function prepare() on a non-object error in my PHP when using PDO to select data that was sent via an AJAX call.
Searching around on StackOverflow I've found many answers to this error, but none work to fix my problem.
The weird part is that the other PHP files use the same PDO calls and work successfully, but this one is giving me the non-object error only.
To note, the PDO connection is identical to the other pages where it works, so I know that's not causing the problem.
Also, I have tested that the AJAX data sent is being received, and that is working too.
PHP Code
$mysql_user = "NotTelling";
$mysql_password = "DefinatelyNotThis";
try
{
$dbh = new PDO("mysql:host=somehost;dbname=somename", $mysql_user, $mysql_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$inPword = $_POST['password'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$loggedin = "";
$password_hash = "";
$loggedinstatus = "";
$pts = "";
function getLoginInfo()
{
$sth = $dbh -> prepare('SELECT pword, loggedin, points FROM login WHERE uname = :uname');
$sth->bindParam(':uname', $username, PDO::PARAM_STR);
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo $row['pword'];
echo $row['loggedin'];
echo $row['points'];
}
$password_hash = $fetch['pword'];
$loggedinstatus = $fetch['loggedin'];
$pts = $fetch["points"];
if($password_hash === null || $loggedinstatus === null || $pts === null)
{
die(json_encode(array("message" => "none")));
}
else
{
return "more";
}
}
function checkLoginCreds()
{
if(crypt($inPword, $password_hash) === $password_hash)
{
switch($loggedinstatus)
{
case "no":
$sel = $dbh->prepare("UPDATE login SET loggedin='yes' WHERE uname = ?");
$sel->execute(array($username));
return "AllGood";
break;
defaut:
return "alreadyin";
break;
}
}
else
{
return "BadLogin";
}
}
if(getLoginInfo() === "more")
{
echo json_encode(array("message" => checkLoginCreds()));
}
getLoginInfo();
}
catch(PDOException $e)
{
echo $e->getMessage();
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
Finally, here's the output when I var_dump() the PDO connection.
object(PDO)#1 (0) {}
For this to work, you need to use the global variable scope, explained here: http://php.net/manual/en/language.variables.scope.php
$mysql_user = "NotTelling";
$mysql_password = "DefinatelyNotThis";
try
{
$dbh = new PDO("mysql:host=somehost;dbname=somename", $mysql_user, $mysql_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$inPword = $_POST['password'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$loggedin = "";
$password_hash = "";
$loggedinstatus = "";
$pts = "";
function getLoginInfo()
{
global $dbh, $username, $password_hash, $loggedinstatus, $pts;
$sth = $dbh -> prepare('SELECT pword, loggedin, points FROM login WHERE uname = :uname');
$sth->bindParam(':uname', $username, PDO::PARAM_STR);
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo $row['pword'];
echo $row['loggedin'];
echo $row['points'];
}
$password_hash = $fetch['pword'];
$loggedinstatus = $fetch['loggedin'];
$pts = $fetch["points"];
if($password_hash === null || $loggedinstatus === null || $pts === null)
{
die(json_encode(array("message" => "none")));
}
else
{
return "more";
}
}
function checkLoginCreds()
{
global $dbh, $inPword, $password_hash, $loggedinstatus, $username;
if(crypt($inPword, $password_hash) === $password_hash)
{
switch($loggedinstatus)
{
case "no":
$sel = $dbh->prepare("UPDATE login SET loggedin='yes' WHERE uname = ?");
$sel->execute(array($username));
return "AllGood";
break;
defaut:
return "alreadyin";
break;
}
}
else
{
return "BadLogin";
}
}
if(getLoginInfo() === "more")
{
echo json_encode(array("message" => checkLoginCreds()));
}
getLoginInfo();
}
catch(PDOException $e)
{
echo $e->getMessage();
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
But this can get messy very quickly.
I suggest you put the variables in an array or using OOP for a more robust solution: http://php.net/manual/en/language.oop5.php
This is how you can define it in a class..
class someClass {
private $db;
public function __construct(){
$this->dbconnect();
}
private function dbconnect() {
try { //try connection
$dbh = new PDO('mysql:host=localhost;dbname=somenane', 'usernane', 'pass');
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbh = $dbh;
} catch (Exception $e) { //connection failed
die("Oh no! It seems we took too long to respond");
}
}
public function getLoginInfo() {
$sth = $this->dbh->prepare('SELECT pword, loggedin, points FROM login WHERE uname = :uname');
$sth->bindParam(':uname', $username, PDO::PARAM_STR);
//cont the code
}
}
Not sure if it's good enough..but it will work..

php script echoing part of the php instead of what intended [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 2 years ago.
I'm having trouble with php script that I've created to insert instances into a database, however I'm getting a trivial output and i dont know how to fix it. the code is:
<?php
try{
$user = 'root';
$pass = null;
$pdo = new PDO('mysql:host=localhost; dbname=divebay', $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$password = sha1($_POST['password']);
$location = %_POST['location'];
$email = $_POST['email'];
$name = $_POST['fname'] . " " . $_POST['surname'];
$check = $pdo->prepare('SELECT * FROM user WHERE username=?');
$check->bindValue(1, $username);
$check->execute();
if($check->fetch(PDO::FETCH_OBJ)){
echo "Account name already exists";
}
else{
$stmt = $pdo->prepare('INSERT INTO user(username, password, location, email, name)
VALUES(:username, :password, :location, :email, :name)');
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':location', $location, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
if($stmt->execute()){
echo "Account created";
}
else{
echo "Account could not be created";
}
}
$pdo = null;
}catch(PDOException $e){
echo $e->getMessage();
}
?>
i would expect the output to be something like "Account created". Instead the output I'm getting this error:
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $username =
$_POST['username']; $password = sha1($_POST['password']);
$location = %_POST['location']; $email = $_POST['email']; $name =
$_POST['fname'] . " " . $_POST['surname']; $check =
$pdo->prepare('SELECT * FROM user WHERE username=?');
$check->bindValue(1, $username); $check->execute();
if($check->fetch(PDO::FETCH_OBJ)){ echo "Account name already exists";
} else{ $stmt = $pdo->prepare('INSERT INTO user(username, password,
location, email, name) VALUES(:username, :password, :location, :email,
:name)'); $stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':location', $location, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
if($stmt->execute()){ echo "Account created"; } else{ echo "Account
could not be created"; } } $pdo = null; }catch(PDOException $e){ echo
$e->getMessage(); } ?>
whats going wrong with this script to cause this?
The only way you'd get that output is if you had written:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
as:
$pdo?>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
by mistake.
YOU HAVE a % INSTEAD OF $ on %_POST['location']
RECOMMENDATION:
Also I HIGHLY recommend wrapping the PDO functions into a class. Here is what I use personally in every single project:
save this to it's own file (ex:sql.class.php)
<?php
class SqlIt{
public $Sql;
public $Response;
private $Host;
private $DBname;
private $User;
private $Pass;
public $NumResults;
public function __construct($Sql, $type, $vars){
if($vars == ""){
$vars = array();
}
try{
$DB = $this->db_connect();
$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DB->prepare($Sql);
$doit = $STH->execute($vars);
$this->Result = $doit;
}
catch(PDOException $e){
echo $e->getMessage();
}
//find function to run
switch($type){
case 'select':
$this->select($STH);
break;
}
}
public function select($query){
$rows = $query->rowCount();
$this->NumResults = $rows;
while($row = $query->fetchObject()){
$this->Response[] = $row;
}
}
//create a separate function for connecting to DB. Private to only this class.
private function db_connect(){
$this->User = 'root';
$this->Pass = '';
$DBH = new PDO("mysql:host=localhost;dbname=divebaby", $this->User, $this->Pass);
return $DBH;
}
}
?>
Then to actually run the statement you placed above you simply right the following code:
$username = $_POST['username'];
$password = sha1($_POST['password']);
$location = $_POST['location'];
$email = $_POST['email'];
$name = $_POST['fname'] . " " . $_POST['surname'];
$getUser = new SqlIt("SELECT * FROM user WHERE username=?","select",array($username));
if($getUser){
echo 'Account name already exists';
}else{
$insertUser = new SqlIt("INSERT INTO user (username,password,location,email,name) VALUES (?,?,?,?,?)","insert",array($username,$password,$location,$email,$name));
if($insertUser){
echo 'Account created!';
}else{
echo 'Account not created.';
}
Missing <?php at the beginning of one of your pages that contains that code with the first line of setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Login script using PDO extension not working

I am unsure if I am doing it properly but I just started working with PDO and I am not able to get my code to work. I continue to get the error "sorry could not connect" and I am unable to figure out what is wrong.
Included below is the code that I am using:
function doRun( $data )
{
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare(' SELECT
username, pass
FROM
testTable
WHERE
username = :name
AND
pass = :pass
');
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
$stmt->execute();
//$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $stmt->fetchColumn();
if($result == false)
{
echo 'sorry could not connect';
}
else
{
$_SESSION['username'] = $user;
echo 'logged in as' . $user;
}
}
catch (PDOException $e)
{
echo "throw";
}
$db = NULL;
}
This would give you 0 rows as it seems that $username and $pass are not defined:
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
^^^^^^^^^
You probably want some elements from $data variable you are feeding to the function as a username and password.
Later on you are using a variable $user that is undefined as well.
What does $data contain?
The reason that you are "unable to connect", even though you are connecting but you're not finding a match, is because your user variables are not defined.
Try the following solution:
<?php
function doRun( $data )
{
$msg = '';
$username = isset($_POST['name']);
$pass = isset($_POST['pass']);
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('
select
username
,pass
from
testTable
where
username = :name
and pass = :pass
');
$stmt->execute(array(':name' => $username, ':pass' => $pass);
$result = $stmt->fetchAll();
if(!empty($result)){
$_SESSION['username'] = $user;
$msg = "logged in as $user";
}else{
$msg = "Unable to connect";
}
} catch (PDOException $e) {
echo "Error: $e";
}
echo $msg
$db = NULL;
}
?>

Categories