PDO fails when called inside a function - php

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.

Related

PHP/MySQL error: Could not execute INSERT INTO with PDO

I'm a beginner to PHP/MySQL trying to insert data into a table via a form, but I keep getting this:
Connected successfully ERROR: Could not execute INSERT INTO foo (firstname, lastname, landline, mobile) VALUES ('', '', ', ').
My limited understanding tells me I'm connecting successfully but nothing's getting into the table. Checking the table confirms this.
I'm trying to send the data from a PHP 7.1 WHMCS server to a remote host running MySQL 5.1.73. I'm pulling a user ID from WHMCS and pre-populating the that field with the idea to send that along with the rest of the form data. I had that field set to "hidden" and "text," no luck.
I even copied/pasted the form to a separate html and tried running everything at the root. No luck.
I used this example as my guide.
form.tpl:
<form method="post" action="includes/action.php">
User ID:<input type ="text" name = "userid" value={$d} readonly> //pulls userID from WHMCS
First name:<input type="text" name="firstname">
Last name:<input type="text" name="lastname">
Landline:<input type="text" name="landline">
Mobile:<input type="text" name="mobile">
<input type="submit" value="Submit"></form>
dbconnect.php:
$servername = "fqdn.com";
$username = "few";
$password = "2many";
try {
$conn = new PDO("mysql:host=$servername;dbname=data_base", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
action.php:
//Open MySql Connection
include "dbconnect.php";
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO foo (userid, firstname, lastname, landline, mobile) VALUES (:userid, :firstname, :lastname, :landline, :mobile)");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':landline', $landline);
$stmt->bindParam(':mobile', $mobile);
// insert a row
$userid = $_POST["userid"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$landline = $_POST["landline"];
$mobile = $_POST["mobile"];
$stmt->execute();
echo "New records created successfully";
} catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
$conn = null;
Sorry for the delay. Here's the solution.
action.php:
public function insertToDb($data)
{
try{
$sql = "INSERT INTO table_name (column1, column2) VALUES ('" . $data['column1']."','" . $data['column2']."')";
$this->con->exec($sql);
if($this->con->lastInsertId() > 0){
return true;
} else {
return "Error: " . $sql . "<br>" . $conn->error;
}
} catch (\PDOException $e) {
return "Insert failed: " . $e->getMessage();
}
}
public function getSingleData($d,$c)
{
try{
$sql = "SELECT * FROM table_name WHERE d='".$d."' AND c='".$c."'";
$query = $this->con->prepare($sql);
$query->execute();
return $query->fetchAll(\PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
return "Error: " . $e->getMessage();
}
}
Edit: #halfer thanks for pointing out the vulnerability.
public function insertToDb($data)
{
try{
$insertdata = [
'column1' => $data['column1'],
'column2' => $data['column2'],
'column3' => $data['column3'],
];
$sql = "INSERT INTO table_name (column1, column2,column3) VALUES (:column1,:column2,:column3)";
$stmt= $this->con->prepare($sql);
$stmt->execute($insertdata);
if($this->con->lastInsertId() > 0){
return true;
} else {
return "Error: " . $sql . "<br>" . $conn->error;
}
} catch (\PDOException $e) {
return "Insert failed: " . $e->getMessage();
}
}
in action.php you are using variables before you have set them.
// insert a row
$userid = $_POST["userid"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$landline = $_POST["landline"];
$mobile = $_POST["mobile"];
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO foo (id, firstname, lastname, landline, mobile) VALUES (:userid, :firstname, :lastname, :landline, :mobile)");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':landline', $landline);
$stmt->bindParam(':mobile', $mobile);
$stmt->execute();

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.

PDO not throwing errors

I have the following code to insert a new record in a database:
<?php
require('comune.php');
$nome = $_POST['nome'];
$username = $_POST['username'];
$segreto = $_POST['password'];
$password = md5($segreto);
$validity = $_POST['validity'];
$ruolo = $_POST['ruolo'];
$funzione = $_POST['funzione'];
list($giorno, $mese, $anno) = explode('/', $validity);
$validity = implode('-', array($anno, $mese, $giorno));
try {
$sql = "INSERT into utenti "
. "(nome,username,segreto,password,validity,ruolo,funzione) "
. "VALUES ('$nome', '$username', '$segreto', '$password', '$validity', '$ruolo', '$funzione')";
$s = $pdo->prepare($sql);
$s->execute();
} catch (PDOException $e) {
$message = "ko";
}
$message = "ok";
//echo $sql;
echo $message;
?>
The issue I am facing is that, even if the query returns an error, $message is "ok". What am I doing wrong??
change your code to
$sql = "INSERT into utenti (nome,username,segreto,password,validity,ruolo,funzione) "
. "VALUES (?,?,?,?,?,?,?)";
$s = $pdo->prepare($sql);
$s->execute([$nome, $username, $segreto, $password, $validity, $ruolo, $funzione]);
echo "ok";
you will have either ok or informative error message

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