PHP pdo insert query not working - php

<?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.

Related

PDO fails when called inside a function

I'm trying to use a function to execute all my PDO queries. I am experiencing a 500 error when using the function. I am able to execute the code successfully if I don't use the function.
you'll notice that the only difference between the working and non-working code blocks below is the use of the function.
Why does the code fail when called inside a function?
WORKS:
try {
$conn = new PDO($dsn, $username, $password, $options);
}
catch (PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
$info = array();
$info['fname'] = $_POST['fname'];
$info['lname'] = $_POST['lname'];
$info['email'] = $_POST['email'];
$info['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
$info['datecreated'] = date("Y-m-d H:i:s");
$sql = "INSERT INTO Users (fname, lname, email, password, datecreated)
VALUES (:fname, :lname, :email, :password, :datecreated)";
try {
$stmt=$conn->prepare($sql);
$stmt->execute($info);
}
catch (PDOException $e)
{
echo $sql . "PDO query failed: <br>" . $e->getMessage();
}
DOESN'T WORK
try {
$conn = new PDO($dsn, $username, $password, $options);
}
catch (PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
$info = array();
$info['fname'] = $_POST['fname'];
$info['lname'] = $_POST['lname'];
$info['email'] = $_POST['email'];
$info['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
$info['datecreated'] = date("Y-m-d H:i:s");
$sql = "INSERT INTO Users (fname, lname, email, password, datecreated)
VALUES (:fname, :lname, :email, :password, :datecreated)";
function pdoquery ($sql, $info){
try {
$stmt=$conn->prepare($sql);
$stmt->execute($info);
}
catch (PDOException $e)
{
echo $sql . "PDO query failed: <br>" . $e->getMessage();
}
}
pdoquery($sql,$info);
Try following
$info = array();
$info['fname'] = $_POST['fname'];
$info['lname'] = $_POST['lname'];
$info['email'] = $_POST['email'];
$info['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
$info['datecreated'] = date("Y-m-d H:i:s");
$sql = "INSERT INTO Users (fname, lname, email, password, datecreated)
VALUES (:fname, :lname, :email, :password, :datecreated)";
function pdoquery ($sql, $info, $conn){
$stmt=$conn->prepare($sql);
$stmt->execute($info);
return $stmt;
}
pdoquery($sql,$info, $conn);
In a nutshell, you forgot to pass $conn to your function.

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

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

Data insert into mysql db table using PDO - Doesn't Insert Data

I'm 'Connected to database'. There is no data in the table, and $result doesn't echo anything. Even though I'm 'Connected to database', the error is as follows:
SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
I've read the relevant postings, with no luck.
<?php
include("/directory outside of html/db.php");
try {
$dbh = new PDO("mysql:host=$host;database=$database", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//try to insert data
$fname = 'BOB';
$lname = 'JONES';
$email = 'me#mymail.com';
$phone = '410-310-3456';
$resident = TRUE;
$age = '25=30';
$zip = '23456';
$result = FALSE;
$stmt = $dbh->prepare('INSERT INTO volunteers
(
lname,
fname,
email,
)
VALUES
(
:lname,
:fname,
:email,
)');
$result = $stmt->execute(array(
':lname' => $lname,
':fname' => $fname,
':email' => $email,
));
echo $result;
//catch any errors from try()
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Use dbname= instead of database= , like this:
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
Alternatively, you can select later a different database with USE, like this:
$dbh->query("use newdatabase");

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