PHP PDO connection failure [duplicate] - php

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 years ago.
Hey, so I am new with PDO, and I cannot figure out why my data will not insert into my tables. Much appreciated!
<?php
include("class.php");
$dbhost = "localhost";
$dbname = "db";
$dbuser = "user";
$dbpass = "pass";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$username = $_POST['username'];
$password = $_POST['password'];
$email = strtolower($_POST['email']);
$firstName = ucwords(strtolower($_POST['firstName']));
$lastName = ucwords(strtolower($_POST['lastName']));
$date = date("Y-m-d");
$hash = Secure::Encrypt($username, $password);
$sql = "INSERT INTO users (username,password,email,firstName,lastName,createDate) VALUES (:username,:password,:email,:firstName,:lastName,:date)";
$q = $conn->prepare($sql);
$q->execute(array(
':username'=>$username,
':password'=>$hash,
':email'=>$email,
':firstName'=>$firstName,
':lastName'=>$lastName,
':date'=>$date));
?>

If all of your table's field names match, I have found that PDO will sometimes fail if one of your array variables are empty.
to find out if any errors are being thrown, add the following after your new PDO declaration (PDO error reporting is silent by default):
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Then add try/catch around each PDO activity as follows:
try {
..Code Here...
}catch (PDOException $err) {
echo $err->getMessage();
}
Final Code:
<?php
include("class.php");
$dbhost = "localhost";
$dbname = "db";
$dbuser = "user";
$dbpass = "pass";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_POST['username'];
$password = $_POST['password'];
$email = strtolower($_POST['email']);
$firstName = ucwords(strtolower($_POST['firstName']));
$lastName = ucwords(strtolower($_POST['lastName']));
$date = date("Y-m-d");
$hash = Secure::Encrypt($username, $password);
$sql = "INSERT INTO users (username,password,email,firstName,lastName,createDate) VALUES (:username,:password,:email,:firstName,:lastName,:date)";
try {
$q = $conn->prepare($sql);
}catch (PDOException $err) {
echo 'Prepare Failed: '.$err->getMessage();
}
try {
$q->execute(array(
':username'=>$username,
':password'=>$hash,
':email'=>$email,
':firstName'=>$firstName,
':lastName'=>$lastName,
':date'=>$date));
}catch (PDOException $err) {
echo 'Execute Failed: '.$err->getMessage();
}
?>
Then please update with any errors you receive :)

Related

can't connect to database with php (mysql) [duplicate]

If I want to put the connection in an external file, what part of this code should be in that external file?
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
This part will go in external file e.g connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
and then your code will look like
require("connection.php");
try {
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Till this part can go to external file, and can be used to open a connection where ever required.

Inserting data into database php [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I'm creating a website and i want to insert data into a phpmyadmin table from a form (method="post") it didn't work i'm connected to the data base but when i type stuff in my form it's not inserted in the table, here's my php part:
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
try {
$conn = new PDO("mysql:host=$hostname;dbname=Database", $username, $password);
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$nom = $_POST['nom'];
$prenom =$_POST['prenom'];
$email = $_POST['email'];
$password = $_POST['password'];
$type = $_POST['type'];
$sql = "INSERT INTO client (nom, prenom, email,password,type)
VALUES ($nom, $prenom, $email, $password , $type)";
}
$conn->connection = null;
?>
I'm not gonna comment much, there's still a lot of learning and
practice that you need to do. Please take your time and go through
this blog, read and practice from it, do not rush take your time
https://phpdelusions.net/pdo
Your code should be looking similar to the one below :
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
try {
$conn = new PDO("mysql:host=$hostname;dbname=Database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo $e->getMessage();
}
$nom = $_POST['nom'];
$prenom = $_POST['prenom'];
$email = $_POST['email'];
$password = $_POST['password'];
$type = $_POST['type'];
try {
$sql = "INSERT INTO client (nom, prenom, email,password,type) VALUES (?,?,?,?,?)";
$stmt = $conn->prepare($sql);
if ($stmt->execute(array(
$nom,
$prenom,
$email,
$password,
$type
))) {
echo "Data inserted";
} else {
echo "could not insert";
}
}
catch (Exception $ex) {
error_log($ex->getMessage());
}
?>

PDO. How to put the connection in an external file

If I want to put the connection in an external file, what part of this code should be in that external file?
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
This part will go in external file e.g connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
and then your code will look like
require("connection.php");
try {
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Till this part can go to external file, and can be used to open a connection where ever required.

Error with PDO in this script | The page turn blank

I'm having a strange problem using PDO in this script. Probably the problem is very simple but i can't find it and it is making me crazy.
The problem is when i launch the script the page turn blank.
<?php
//PDO
if(isset($_POST['submit'])) {
// test row
$password = $_POST['upassword'];
$email = $_POST['email'];
$_SESSION['email'] = $email;
$servername = "localhost";
$username = "root";
$password = "passwordxyz";
$dbname = "abcd";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $conn->prepare('SELECT `password` FROM `users` WHERE `email` = :email');
$statement->bindParam(':email', $email);
$statement->execute();
while($row = $statement->fetch() ){
echo 'ok';
}
}
}
?>
Please help me to solve the problem.
Thank you.
You have try clause but no catch which is what is generating the error.
<?php
//PDO
if(isset($_POST['submit'])) {
$password = $_POST['upassword'];
$email = $_POST['email'];
$_SESSION['email'] = $email;
$servername = "localhost";
$username = "root";
$password = "passwordxyz";
$dbname = "abcd";
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $conn->prepare('SELECT `password` FROM `users` WHERE `email` = :email');
$statement->bindParam(':email', $email);
$statement->execute();
while($row = $statement->fetch() ){
echo 'ok';
}
}
catch(Exception $e){
//change from general to specific exception and handle here
}
}

Convert php code with Mysql ext to PDO won't work

I have decided for security to convert my simple php with mysql code to PDO,since it will tighten my security.My old code:
$host = "localhost";
$user = "username";
$pass = "pass";
$database = "mydatabase";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$name=$_POST['name'];
$message=$_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$query="INSERT INTO table (date_time, name, message,ip) VALUES (NOW(),'$name','$message','$ip')";
If (mysql_query($query,$linkID)){
//Success
}else{
//Failure
}
My new code is:
$hostname = 'localhost';
$username = 'username';
$password = 'pass';
$dbname = 'mydatabase';
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
if($_POST['name'] && $_POST['message']) {
$name = $_POST['name'];
$message = $_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO table (date_time, name, message,ip)VALUES (NOW(), :name, :message,'$ip')";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':message', $message, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "OK";
}
}
It's very strange that when i point my browser to index.php?name=someName&message=someMessage my PDO code won't echo a single thing(even echo "ok" ) or an error so i can fugure out where is the problem.
I can confirm that no data is inserted to the database.
I've even added try catch but nothing changed. My php is supporting PDO and the simple Mysql code is working.
Any ideas? Thanks
In your case,
if($_POST['name'] && $_POST['message']) {
Should be:
if($_GET['name'] && $_GET['message']) {

Categories