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

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

Related

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.

Can't insert data via PDO using associative array

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.

php PDO prepare(" INSERT ..(variables ) VALUES(?,?,) produces an error need assistance

$query = $this->link->prepare("INSERT INTO surveys (`username`,`inspected`,
`comments`,`ip_address`,`date`,`time`)
VALUES '(?,?,?,?,?,?)';);
$values = array ($username,$inspected,$comments,$ip_address,$date,$time);
var_dump($query);$rowCount = $query->rowCount();
$return $rowCount;
You can base yourself on the following which I've prepared for you.
Sidenote: I'm not entirely sure as to why you want to use rowCount() for, so I left it out for now.
If you're looking to check if a record exists using rowCount(), let me know.
The following method works to insert data into a database, which is based on a method I use.
<?php
$dbname = 'xxx';
$username = 'xxx';
$password = 'xxx';
try {
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit( $e->getMessage() );
}
$sql = "INSERT INTO surveys (
username,
inspected,
comments,
ip_address,
date,
time
) VALUES (
:username,
:inspected,
:comments,
:ip_address,
:date,
:time)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':inspected', $_POST['inspected'], PDO::PARAM_STR);
$stmt->bindParam(':comments', $_POST['comments'], PDO::PARAM_STR);
$stmt->bindParam(':ip_address', $_POST['ip_address'], PDO::PARAM_STR);
$stmt->bindParam(':date', $_POST['date'], PDO::PARAM_STR);
$stmt->bindParam(':time', $_POST['time'], PDO::PARAM_STR);
// $stmt->execute();
$stmt->execute(array(':username' => $_POST['username'],':inspected' => $_POST['inspected'],':comments' => $_POST['comments'],
':ip_address' => $_POST['ip_address'],':date' => $_POST['date'],':time' => $_POST['time']));
if($stmt != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}

Change mysql_ functions with PDO

I need to rewrite my php code with mysql_* functions with PDO so I have:
<?php
$con = mysql_connect('localhost', 'gmaestro_agro', 'pass') or die('Error connecting to server');
mysql_select_db('gmaestro_agro', $con);
mysql_select_db('gmaestro_agro', $con);
$query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
$query .= "'".mysql_real_escape_string($_POST['Name']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Gender']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Age']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Donuts_eaten']);
$query .= "')";
$result = mysql_query($query);
if($result != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
?>
and I try to write this but with PDO function like this:
<?php
/* Your Database Name */
$dbname = 'gmaestro_agro';
/* Your Database User Name and Passowrd */
$username = 'gmaestro_agro';
$password = 'pass';
$stmt = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO stat(Name,
Gender,
Age,
Donuts eaten
) VALUES (
:Name,
:Gender,
:Age,
:Donuts_eaten)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':Gender', $_POST['gender'], PDO::PARAM_STR);
$stmt->bindParam(':Age', $_POST['age'], PDO::PARAM_STR);
// use PARAM_STR although a number
$stmt->bindParam(':Donuts_eaten', $_POST['Donuts_eaten'], PDO::PARAM_STR);
$stmt->execute();
if($stmt != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
?>
I dont get any error just nothing happend? Any idea how to solve my problem?
Edit (successful test code)
Table and data creation codes used for the successful insertion (test).
Column Donuts_eaten has been used with an underscore instead of a space.
You can base yourself on this:
Table creation codes in PHPmyadmin
Note: Change your_db_name to your Database name.
CREATE TABLE `your_db_name`.`stat` (
`Name` VARCHAR( 255 ) NOT NULL ,
`Gender` VARCHAR( 255 ) NOT NULL ,
`Age` INT NOT NULL ,
`Donuts_eaten` INT NOT NULL
) ENGINE = MYISAM
HTML form
Note: <input type="text" name="Donuts_eaten"> - Donuts_eaten is not the same as donuts_eaten notice the lowercase d
<form action="insert.php" method="post">
Name:
<input type="text" name="name">
<br>
Gender:
<input type="text" name="gender">
<br>
Age:
<input type="text" name="age">
<br>
Donuts eaten:
<input type="text" name="Donuts_eaten">
<br>
<input type="submit" name="submit" value="Submit">
</form>
PHP/SQL
<?php
/* Your Database Name */
$dbname = 'dbname'; // change this
/* Your Database User Name and Passowrd */
$username = 'username'; // change this
$password = 'password'; // change this
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO stat (Name,
Gender,
Age,
Donuts_eaten
) VALUES (
:Name,
:Gender,
:Age,
:Donuts_eaten)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':Gender', $_POST['gender'], PDO::PARAM_STR);
$stmt->bindParam(':Age', $_POST['age'], PDO::PARAM_STR);
// use PARAM_STR although a number
$stmt->bindParam(':Donuts_eaten', $_POST['Donuts_eaten'], PDO::PARAM_STR);
// old execute
// $stmt->execute();
$stmt->execute(array(':Name' => $_POST['name'],':Gender' => $_POST['gender'],':Age' => $_POST['age'],':Donuts_eaten' => $_POST['Donuts_eaten']));
if($stmt != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
?>
Original answer
You need to wrap Donuts eaten in backticks (for your column name), due to the space.
$sql = "INSERT INTO stat(Name,
Gender,
Age,
`Donuts eaten`
) VALUES (
:Name,
:Gender,
:Age,
:Donuts_eaten)";
Using spaces in column names is discouraged. Use an underscore instead for your table's column.
Also, change:
$stmt = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
to:
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
because you're using $pdo in $stmt = $pdo->prepare($sql);
You are mixing up your variables, $pdo is undefined / not your database connection.
You can probably solve it by using:
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
instead of:
$stmt = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
And if a table or column name contains spaces, you need to quote them in backticks:
Gender,
Age,
`Donuts eaten`
) VALUES (
But with the first change, PDO should throw an exception to show you this problem.

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

Categories