How to put a condition in my pdo code - php

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!';

Related

PHP fails at inserting values into database

I'm using a WordPress theme for my site, but customizing it has given me such a headache that we are trying to use our own hand written from instead of the one provided by WordPress.
I have written a php-script that should insert values from this form into a custom table in a custom database outside of the wordpress database. How ever when I try to run it I get no error messages, and no data is inserted into the database.
my PHP code, please not that I have changed the $user and $pass to not show here. I've tested the login info used in this script via terminal on my database, and it worked fine. See the full file here page.sign.php
if(isset($_POST['submit'])) {
$lastname = $_POST["lname"];
$firstname = $_POST["fname"];
$email = $_POST["email"];
$affiliation = $_POST["affiliation"];
$country = $_POST["X"];
$position = $_POST["position"];
$hindex = $_POST["scholar"];
$gender = $_POST["optionsRadios"];
$city = $_POST["city"];
$webpage = $_POST["webpage"];
$newsletter = $_POST["newsletter"];
//Source https://gist.github.com/adrian-enspired/385c6830ba2932bc36a2
$host = "localhost";
$dbname = "petition";
$user = "<username>";
$pass = "<password>";
$charset = "UTF8MB4"; // if your db does not use CHARSET=UTF8MB4, you should probably be fixing that
$dsn = "mysql:host={$host};dbname={$dbname};charset={$charset}";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
echo "<h1>Error connecting to the database </h1>";
}
$stmt = $pdo->prepare("INSERT INTO petitioners (lastname, firstname, email, affiliation, country, position, hindex, gender, city, webpage, newsletter)
VALUES
(:lastname, :firstname, :email, :affiliation, :country, :position, :hindex, :gender, :city, :webpage, :newsletter)");
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':firstname', $firsname);
$stmt->bindParam(':email',$email);
$stmt->bindParam(':affliation',$affiliation);
$stmt->bindParam(':country',$country);
$stmt->bindParam(':position',$position);
$stmt->bindParam(':hindex',$hindex);
$stmt->bindParam(':gender',$gender);
$stmt->bindParam(':city',$city);
$stmt->bindParam(':webpage',$webpage);
$stmt->bindParam(':newsletter',$newsletter);
$stmt->execute();
echo "<h1>Signatory succefully registered</h1>";
$stmt->close();
$conn->close();
}

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.

Uncaught exception 'PDOException' error in my pdo

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.

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