Can't insert data via PDO using associative array - php

That's how I'm trying to do it:
database.php:
<?php
$host = "host";
$user = "user";
$pass = "password";
$dbname = "database";
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
file that must insert data:
<?php
include 'database.php';
$_POST['name'] = 'test';
$_POST['message'] = 'test';
$_POST['date'] = 'test';
var_dump($_POST);
if(isset($_POST['name']) && isset($_POST['message'])){
$data = array(
'name' => $_POST['name'],
'shout' => $_POST['message'],
'date' => $_POST['date']
);
$STH->bindParam(':name', $_POST['name']);
$STH->bindParam(':message', $_POST['message']);
$STH->bindParam(':date', $_POST['date']);
try {
$STH = $DBH->prepare("INSERT INTO shouts (name, message, date) value (:name, :message, :date)");
$STH->execute($data);
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
According to this http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059 it should accept associative array. But instead it does nothing and says that I have an error in this line:
$STH = $DBH->("INSERT INTO shouts (name, message, date) value (:name, :message, :date)");
What can be causing it, and how I can actually use an associative array to insert data into MySQL database using PDO?

Hmmmm... There are some flaws I can see:
database.php
$host = "us-cdbrbababababableardb.net";
$user = "b9bababababefc";
$pass = "9c4ababab";
$dbname = "heroku_aabababab49";
$DBH = null;
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
file that must insert data
<?php
include 'database.php';
$_POST['name'] = 'test';
$_POST['message'] = 'test';
$_POST['date'] = 'test';
var_dump($_POST);
if(isset($_POST['name']) && isset($_POST['message'])){
$data = array(
'name' => $_POST['name'],
'shout' => $_POST['message'],
'date' => $_POST['date']
);
try {
// NOTICE: prepare() used and VALUES instead of VALUE
$STH = $DBH->prepare("INSERT INTO shouts (name, message, date) values (:name, :message, :date)");
$STH->bindParam(':name', $_POST['name']);
$STH->bindParam(':message', $_POST['message']);
$STH->bindParam(':date', $_POST['date']);
// NOTICE: $data has allready been supplied by bindParam()
$STH->execute();
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
These are just the first few things I could find wrong with the code... Try reading up on the PDO tutorials and functions for better info on what they would need as input.

Related

keep printing over and over connected to database

Update: my code works if I put my database file in script file, so not sure why is it not working if I have different file
I have a csv file that I parse at input as in command line and use that file (csv) to insert those values of csv (name, surname and email) to mysql. When I run my code it keep printing over and over until it runs out of memory connected to database what am I doing wrong? ANy help is appreciated.
script.php
<?php
require "database.php";
$options = ['file:'];
$values = getopt(null, $options);
$lines = file($values['file'], FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$csv = array_map('str_getcsv', $lines);
$col_names = array_shift($csv);
$users = [];
foreach($csv as $row) {
$users[] = [
$col_names[0] => ucfirst(strtolower($row[0])),
$col_names[1] => ucfirst(strtolower($row[1])),
$col_names[2] => filter_var(strtolower($row[2]), FILTER_VALIDATE_EMAIL),
];
$stmt = $dbh->prepare("INSERT INTO users(name, surname, email)
VALUES(:name, :surname, :email)");
$stmt->bindParam(':name', $col_names[0]);
$stmt->bindParam(':surname', $col_names[1]);
$stmt->bindParam(':email', $col_names[2]);
$stmt->execute();
}
$dbh = null;
?>
database.php
<?php
$hostname = 'localhost';
$username = 'root';
$password = 'yourpasswordhere';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=userDetails", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to Database';
} catch (PDOException $e) {
echo $e->getMessage();
}
?>

why php-pdo don't insert values [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 years ago.
I'm setting to do a simple query using PDO. However, when I run it, it does not insert. The database is called "famous" and the table is called "pessoas" containing only two columns called (codigo and nome).The connection works, but when I execute it return "Error to save".
<?php
function getConnection(){
$dsn = 'mysql:host=localhost;bdname=pessoas';
$user = 'root';
$password = 'init4289';
try{
$pdo = new PDO($dsn, $user, $password);
echo 'SUCESSO AO CONECTAR!';
return $pdo;
}catch(PDOExeption $ex){
echo 'erro: '. $ex->getMessage();
}
}
?>
#end page "conexao_pdo.php"
<?php
include 'conexao_pdo.php';
$conn = getConnection();
$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');
if($stmt->execute()){
echo 'Success to save';
}else{
echo '<p>'.'Error to save';
}
?>
You may consider the following:
probably it's just a typing error - bdname should be dbname in 'mysql:host=localhost;bdname=pessoas'
database and table names - 'famous' and 'pessoas' in the question, 'pessoas' and 'famous' in the code
include exception handling with PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
your function getConnection() should return false on failure
Code, based on your question:
<?php
function getConnection(){
$dsn = 'mysql:host=localhost;dbname=pessoas';
$user = 'root';
$password = 'init4289';
try {
$pdo = new PDO(
$dsn,
$user,
$password,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
echo 'SUCESSO AO CONECTAR!';
} catch (PDOExeption $ex){
echo 'Error: '. $ex->getMessage();
return false;
}
return $pdo;
}
?>
<?php
include 'conexao_pdo.php';
// Connection
$conn = getConnection();
if ($conn === false) {
exit;
}
// Statement
try
$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');
if ($stmt->execute()) {
echo 'Success to save';
} else {
echo '<p>'.'Error to save';
}
} catch (PDOExeption $ex){
die ('Error: '. $ex->getMessage());
}
?>

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 Insert Doesn't Throw Error or Insert Form Data

I am making the switch from MYSQL to PDO and on my form it will not insert the form data into the DB. What is strange is that it doesn't throw any errors but redirects to the success page without inserting the data. Here is my code:
<?php
session_start();
/*** mysql hostname ***/
$hostname = 'XXXXXXX.hostedresource.com';
/*** mysql username ***/
$username = 'XXXXXX';
/*** mysql password ***/
$password = 'XXXXXXXX';
try {
$pdo = new PDO("mysql:host=$hostname;dbname=XXXXXX;charset=utf8", $username, $password);
array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
/*** echo a message saying we have connected ***/
//echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$loan_amount = trim($_POST['loan_amount']);
$loan_type = trim($_POST['loan_type']);
$debt_amount = trim($_POST['debt_amount']);
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$zip = trim($_POST['zip']);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
try {
$sql="INSERT INTO leads (loan_amount, loan_type, debt_amount, first_name, last_name, email, phone, zip, reg_date) VALUES (:loan_amount, :loan_type, :debt_amount, :first_name, :last_name, :email, :phone, :zip, NOW())";
$statement = $pdo->prepare($sql);
$statement->bindValue(':loan_amount', $loan_amount);
$statement->bindValue(':loan_type', $loan_type);
$statement->bindValue(':debt_amount', $debt_amount);
$statement->bindValue(':first_name', $first_name);
$statement->bindValue(':last_name', $last_name);
$statement->bindValue(':email', $email);
$statement->bindValue(':phone', $phone);
$statement->bindValue(':zip', $zip);
$statement->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
exit();
}
header('Location: /success.php');
}
?>
The issue is with syntax:
$pdo = new PDO("mysql:host=$hostname;dbname=XXXXXX;charset=utf8", $username, $password);
array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
You have a closing parenthesis and semi-colon at the end of your constructor which is breaking your code. You either need:
$pdo = new PDO("mysql:host=$hostname;dbname=XXXXXX;charset=utf8", $username, $password,
array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
OR
$pdo = new PDO("mysql:host=$hostname;dbname=XXXXXX;charset=utf8", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

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

Categories