Inserting data into database php [duplicate] - php

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

Related

PHP Unable to insert data into database using PDO

I want to insert data given by the user into the database when I use simple mysqli it works perfectly but when I use PDO data is inserted into the database.
<?php
$server = 'localhost';
$username = 'root';
$pass = '';
$database = 'db';
try {
$conn = new PDO("mysql:host=$server;dbname=$database", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$name = '';
$password = '';
$email = '';
$uid = '';
$sql = "INSERT INTO users(name,email,password,userid) VALUES(?,?,?, ?)";
if (isset($_POST['username'])) {
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$newpass = hash("sha256", $password);
if ($name != '' && $password != '' && $email != '') {
$insertUser = $conn->prepare($sql);
$insertUser->execute($name, $email, $password, $uid);
}
}
$conn = null;
Just use parameters array:
$sql = "INSERT INTO users(name,email,password,userid) VALUES(?, ?, ?, ?)";
if(isset($_POST['username']))
{
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$newpass = hash("sha256", $password);
if($name!='' && $password!='' && $email!='')
{
$insertUser = $conn->prepare($sql);
// use ARRAY instead plain variables
$insertUser->execute([$name, $email, $password, $uid]);
}
}
Execute PHP online

using variable inside mysql update query in php

<?php
require 'functions/connection.php';
$conn = Connect();
$e_id = $conn->real_escape_string($_POST['e_id']);
$first_name = $conn->real_escape_string($_POST['first_name']);
$last_name = $conn->real_escape_string($_POST['last_name']);
$e_salary = $conn->real_escape_string($_POST['e_salary']);
$e_startdate = $conn->real_escape_string($_POST['e_startdate']);
$e_department = $conn->real_escape_string($_POST['e_department']);
$sql = "UPDATE employee SET firstname='$first_name' WHERE id=$e_id";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
I'm trying to use the first_name variable inside the update query.
I tried echo the variable and its working...
this is my connection code that im using.
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "company";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
if i i replace the variable with anything between "" the database is getting updated
I'd suggest making it more secure and using prepared statements. This is an example using mysqli, but I prefer PDO:
<?php
require 'functions/connection.php';
$conn = Connect();
// Prepare the query
$myQuery = $conn->prepare("UPDATE employee SET firstname=? WHERE id=?");
$e_id = $conn->real_escape_string($_POST['e_id']);
$first_name = $conn->real_escape_string($_POST['first_name']);
$last_name = $conn->real_escape_string($_POST['last_name']);
$e_salary = $conn->real_escape_string($_POST['e_salary']);
$e_startdate = $conn->real_escape_string($_POST['e_startdate']);
$e_department = $conn->real_escape_string($_POST['e_department']);
// Bind your variables to the placemarkers (string, integer)
$myQuery->bind_param('si', $first_name, $e_id);
if ($myQuery->execute() == false) {
echo 'Error updating record: ' . $mysqli->error;
}
else {
echo 'Record updated successfully';
}
$myQuery->close();
?>
Note: The 'cleansing' you're doing in the middle I have left, but it's not really necessary with prepared statements.
functions/connection.php (Now an object):
<?php
class Connect
{
private $dbhost = "localhost";
private $dbuser = "root";
private $dbpass = "";
private $dbname = "company";
public $conn;
public function __construct()
{
if($this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname))
{
//connection established
//do whatever you want here
}
else
{
//Error occurred
die($this->conn->error);
}
}
//other functions here
}
?>
Change mysqli_query to: $conn->conn->query($sql);
Prepared statement:
Avoid SQLI injection
if($stmt = $conn->conn->prepare("UPDATE employee SET firstname = ? WHERE id = ?"))
{
$stmt->bind_param('si', $first_name, $e_id);
$stmt->execute();
echo $stmt->affected_rows;
}
Final code:
<?php
require 'functions/connection.php';
$conn = new Connect();
$e_id = $conn->conn->real_escape_string($_POST['e_id']);
$first_name = $conn->conn->real_escape_string($_POST['first_name']);
$last_name = $conn->conn->real_escape_string($_POST['last_name']);
$e_salary = $conn->conn->real_escape_string($_POST['e_salary']);
$e_startdate = $conn->conn->real_escape_string($_POST['e_startdate']);
$e_department = $conn->conn->real_escape_string($_POST['e_department']);
if($stmt = $conn->conn->prepare("UPDATE employee SET firstname = ? WHERE id = ?"))
{
$stmt->bind_param('si', $first_name, $e_id);
$stmt->execute();
echo $stmt->affected_rows;
}
$conn->conn->close();
?>

PHP function not passing data to MySQL

I've setup a sign up page to register users, its passed from HTML and into PHP
however the PHP function is not passing it over to the MySQL database
<?php
try{
$db = new PDO ("mysql:host=localhost;dbname=car_rental;port=3306","root","");
}
catch (Exception $e){
echo "SQL is Off";
exit;
}
echo "success";
try{
$trial = "INSERT INTO users (firstName) VALUES ('trial')";
}
catch (Exception $e){
echo "doesnt work..";
}
echo "works?";
try{
function NewUser()
{
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$age = $_POST['age'];
$email = $_POST['email'];
$password = $_POST['pass'];
$query = "INSERT INTO users (firstName,lastName,age,email,pass) VALUES ('$firstName','$lastName','$age','$email','$password')";
echo"user created";
}
}
catch (PDOException $e)
{
echo "ERROR -_-";
}
?>
is this the correct implementation to execute a sql query in PHP?
function NewUser()
{
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$age = $_POST['age'];
$email = $_POST['email'];
$password = $_POST['pass'];
$query = "INSERT INTO users (firstName,lastName,age,email,pass) VALUES ('$firstName','$lastName','$age','$email','$password')";
$db->exec($query);
echo"user created";
}
Thanks
You just write queries, but forgot to execute
$db = new PDO ("mysql:host=localhost;dbname=car_rental;port=3306","root","");
$query = "INSERT INTO users (firstName,lastName,age,email,pass) VALUES ('$firstName','$lastName','$age','$email','$password')";
$db->query($db); // executes it

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']) {

PHP PDO connection failure [duplicate]

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

Categories