Uncaught exception 'PDOException' error in my pdo - php

after running my code i got this kind of error, can anyone help me fix it please. The error starts after putting a code to filter if the email is duplicate or not in the database.
here is the error i got:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = #$_POST['name'];
$age = #$_POST['age'];
$address = #$_POST['address'];
$gender = #$_POST['gender'];
$email = #$_POST['email'];
$dupesql = "SELECT * FROM students WHERE email = :email ";
$dupesql = $dbc->prepare($dupesql);
$dupesql->bindParam(':name', $email);
$dupesql->execute();
$num_rows = $dupesql->rowCount();
if($num_rows === 0)
{
echo "1";
$q = "INSERT INTO students(name, age, address, gender, email ) VALUES(:name, :age, :address, :gender, :email)";
$query = $dbc->prepare($q);
$query->bindParam(':name', $name);
$query->bindParam(':age', $age);
$query->bindParam(':address', $address);
$query->bindParam(':gender', $gender);
$query->bindParam(':email', $email);
$results = $query->execute();
}else{
echo "0";
exit;
}
?>

Well you are facing this error because you are using a wrong parameter in your query.
$dupesql->bindParam(':name', $email);
:name doesn't exists so it should :email.

Related

Unable to INSERT data from form

I have been working on this process for the past two days and might be missing something very obvious, so I am hoping for some extra eyes to spot the issue.
My form is passing the fields and I am able to connect to my database and echo out both the $_POST data (var_dump($_POST)) and also echo out the variables successfully. I get my connection message at line 35, but the script does not proceed to the SQL INSERT section. Any suggestions would be greatly appreciated
<?php
session_start();
//Get user id for posting to record
$_SESSION['id'] = $id;
//Get posted data and sanitize
$custId = filter_var($_POST['cust_id'], FILTER_SANITIZE_STRING);
$name = filter_var($_POST['_name'], FILTER_SANITIZE_STRING);
$ordDate = filter_var($_POST['ordDate'], FILTER_SANITIZE_STRING);
$reqDate = filter_var($_POST['reqDate'], FILTER_SANITIZE_STRING);
$bAddr = filter_var($_POST['_baddr'], FILTER_SANITIZE_STRING);
$bCont = filter_var($_POST['_contact'], FILTER_SANITIZE_STRING);
$bEmail = filter_var($_POST['_email'], FILTER_SANITIZE_STRING);
$bFax = filter_var($_POST['_fax'], FILTER_SANITIZE_STRING);
$bMobile = filter_var($_POST['_mobile'], FILTER_SANITIZE_STRING);
$bPhone = filter_var($_POST['_phone'], FILTER_SANITIZE_STRING);
$dAddr = filter_var($_POST['_daddr'], FILTER_SANITIZE_STRING);
$dCont = filter_var($_POST['_dContact'], FILTER_SANITIZE_STRING);
$bEmail = filter_var($_POST['_dEmail'], FILTER_SANITIZE_STRING);
$bMobile = filter_var($_POST['_dMobile'], FILTER_SANITIZE_STRING);
$bPhone = filter_var($_POST['_dPhone'], FILTER_SANITIZE_STRING);
$notes = filter_var($_POST['_delNotes'], FILTER_SANITIZE_STRING);
$servername = "localhost";
$database = "edwardm3_generation";
$username = "edwardm3_gen";
$password = "*********";
$sql = "mysql:host=$servername;dbname=$database;";
$dsn_Options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
//
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$my_Db_Connection = new PDO($sql, $username, $password, $dsn_Options);
echo "Connected successfully";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
$sql2 = "INSERT INTO orders (custId, orderDate, reqDate, bAddr, bCont, bFax, bMobile, bPhone, dAddr, dCont, dEmail, dMobile, dPhone, notes, orderedBy) VALUES (:custId, :ordDate, :reqDate, :bAddr, :bCont, :bFax, :bMobile, :bPhone, :dAddr, :dCont, :dEmail, :dMobile, :dPhone, :notes, :id)";
$stmt = $my_Db_Connection->prepare($sql2);
$stmt ->bindParam(':custId', $custId, PDO::PARAM_INT);
$stmt ->bindParam(':ordDate', $ordDate, PDO::PARAM_STR);
$stmt ->bindParam(':reqDate', $reqDate, PDO::PARAM_STR);
$stmt ->bindParam(':bAddr', $bAddr, PDO::PARAM_STR);
$stmt ->bindParam(':bCont', $bCont, PDO::PARAM_STR);
$stmt ->bindParam(':bFax', $bFax, PDO::PARAM_STR);
$stmt ->bindParam(':bMobile', $bMobile, PDO::PARAM_STR);
$stmt ->bindParam(':bPhone', $bPhone, PDO::PARAM_STR);
$stmt ->bindParam(':dAddr', $dAddr, PDO::PARAM_STR);
$stmt ->bindParam(':dCont', $dCont, PDO::PARAM_STR);
$stmt ->bindParam(':dEmail', $dEmail, PDO::PARAM_STR);
$stmt ->bindParam(':dMobile', $dMobile, PDO::PARAM_STR);
$stmt ->bindParam(':dPhone', $dPhone, PDO::PARAM_STR);
$stmt ->bindParam(':notes', $notes, PDO::PARAM_STR);
$stmt ->bindParam(':create', $create, PDO::PARAM_INT);
if ($stmt ->execute()) {
echo "New record created successfully";
} else {
echo "Unable to create record";
}
?>

PHP pdo insert query not working

<?php
// DATABASE-HOSTNAME-OR-IPADDRESS-GOES-HERE
// MYSQL-DBNAME-GOES-HERE
class LoginHandler {
public $dbHostname = 'localhost';
public $dbDatabaseName = 'employee101';
public $user = 'root';
public $password = 'root';
public function handleRequest($arg) {
$username = '123';
$password2 = '123';
$fname = 'John';
$lname = 'Doe';
$age = '18';
if ( ! $username ) {
$this->fail();
return;
}
try {
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$sql="SELECT * FROM `employee_data` WHERE `username`='$username'";
$stmt = $pdo->query($sql);
if ( $stmt === false ) {
echo "DB Critical Error";
return;
}
elseif ( $stmt->rowCount() > 0 ) {
echo "user already exists";
return;
}
else {
echo "User created";
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES ($fname, $lname, $age, $username, $password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam($fname, $_POST[$fname], PDO::PARAM_STR);
$stmtz->bindParam($lname, $_POST[$lname], PDO::PARAM_STR);
$stmtz->bindParam($age, $_POST[$age], PDO::PARAM_STR);
$stmtz->bindParam($username, $_POST[$username], PDO::PARAM_STR);
$stmtz->bindParam($password2, $_POST[$password2], PDO::PARAM_STR);
$resultzzx = $stmtz->execute();
return;
}
}
catch(PDOException $e) {
$this->log('Connection failed: ' . $e->getMessage());
echo "DB Critical Error";
}
}
function log($msg) {
file_put_contents("login.log", strftime('%Y-%m-%d %T ') . "$msg\n", FILE_APPEND);
}
}
$handler = new LoginHandler();
$handler->handleRequest($_POST);
?>
When attempting to use this script above, I get the echo that the user was created, but even when refreshing the table, the new entry doesn't show up.
Now, if i change the values line to be the following, it will work and show the new entry.
('John', 'Doe', '18', $username, $password2)";
What am i doing wrong? I need the first name, last name and age entries to not be concrete, as i will be obtaining them from a POST on my android device. The whole purpose of this script is to create the user and it's records if it doesn't already exist.
You have various mistakes.
1) You are not binding your parameters correctly. To bind them correctly, you place a :variablename in the position you want to include the variable. Usually the "variablename" should be the same as the one you are obtaining from the $_POST superglobal so that the code is cleaner and more readable.
2) You are not obtaining the values from the $_POST superglobal correctly. The key values you place inside are strings, and by placing an empty $fname variable, you are not going to obtain a correct result. It would only work if you had coding saying $fname = 'fname' somewhere up top hidden from us, however that code itself would be unadvised since it is unnecessary and only makes the source code larger.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES (:fname, :lname, :age, :username, :password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host=
{$this>dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':fname', $_POST['fname']);
$stmtz->bindParam(':lname', $_POST['lname']);
$stmtz->bindParam(':age', $_POST['age']);
$stmtz->bindParam(':username', $_POST['username']);
$stmtz->bindParam(':password2', $_POST['password2']);
I hope that helps.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password) VALUES (:name, :sumame, :age, :username, :password)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':name', $fname);
$stmtz->bindParam(':sumame', $lname);
$stmtz->bindParam(':age', $age);
$stmtz->bindParam(':username', $username);
$stmtz->bindParam(':password', $password2);
$resultzzx = $stmtz->execute();
return;
After reviewing the link Fred posted in the comment above, i've modified it to work fine, thanks.

How to put a condition in my pdo code

I want to do is when a user successfully registered my pdo will have a condition if its successful or not.
My problem how to put a if else condition in pdo if the user is successful or not in registering an account.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = #$_POST['name'];
$age = #$_POST['age'];
$address = #$_POST['address'];
$gender = #$_POST['gender'];
$imageName = #$_FILES['image']['name'];
$q = "INSERT INTO students(name, age, address, gender, imageName ) VALUES(:name, :age, :address, :gender, :image)";
$query = $dbc->prepare($q);
$query->bindParam(':name', $name);
$query->bindParam(':age', $age);
$query->bindParam(':address', $address);
$query->bindParam(':gender', $gender);
$query->bindParam(':image', $imageName);
$results = $query->execute();
?>
My problem how to put a if else condition in pdo if the user is successful or not in registering an account.
PDOStatement::execute() returns boolean true or false depending on the result.
You should be able to check $results for the results...
echo $results ? 'User successfully registered' : 'Error registering user!';

PDO Insert not working (PHP/MySQL)

After days of trial and error, I finally replaced my standard mysql code with PDO. Everything seems to be working just fine except for the last part where the app needs to INSERT user (name, email and time of signup) into database. After clicking submit, page just turns blank.
I don't see what is wrong with the code, so I would appreciate if you could help me out.
<?php
////Database connection values
$dsn = 'mysql:host=host; dbname=name; charset=utf8';
$db_user = 'username';
$db_pass = 'password';
//Database connection
$db = new PDO($dsn, $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Enable Exception error mode
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // Use PDO safely = Turn off prepare emulation
// Databse connection check
if($db){
print "connected to the db " . "<br />";
}
//Declare values
$name = "";
$email = "";
$userMsg = "";
if ($_POST['name'] != "") {
$name = $_POST['name'];
$email = $_POST['email'];
//MySQL SELECT Query
$stmt = $db -> prepare ("SELECT * FROM newsletter WHERE email=?");
$stmt-> bindValue(1, $email);
$stmt -> execute ();
//Error - No email
if (!$email) {
$userMsg = '<br /><br /><h4><font color="FF0000">Please type an email address ' . $name . '.</font></h4>';
} // End email-input check
//Error - Email already in the system
else if ($stmt -> rowCount() > 0) {
$userMsg = '<br /><br /><h4><font color="FF0000">' . $email . ' is already in the system.</font></h4>';
} // End Row check
//OK - insert user into database
else {
$insert = $db -> prepare ("INSERT INTO newsletter (name, email, dateTime) VALUES(:name, :email, ,NOW())");
$insert -> execute(array(':name' => $name, ':email' => $email));
//Success! - Notify user
$userMsg = '<br /><br /><h4><font color="0066FF">Thanks ' . $name . ', you have been added successfully.</font></h4>';
$name = "";
$email = "";
} // End INSERT
}
?>
VALUES(:name, :email, ,NOW())"
should be
VALUES(:name, :email, NOW())"

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

Categories