Unable to INSERT data from form - php

I have been working on this process for the past two days and might be missing something very obvious, so I am hoping for some extra eyes to spot the issue.
My form is passing the fields and I am able to connect to my database and echo out both the $_POST data (var_dump($_POST)) and also echo out the variables successfully. I get my connection message at line 35, but the script does not proceed to the SQL INSERT section. Any suggestions would be greatly appreciated
<?php
session_start();
//Get user id for posting to record
$_SESSION['id'] = $id;
//Get posted data and sanitize
$custId = filter_var($_POST['cust_id'], FILTER_SANITIZE_STRING);
$name = filter_var($_POST['_name'], FILTER_SANITIZE_STRING);
$ordDate = filter_var($_POST['ordDate'], FILTER_SANITIZE_STRING);
$reqDate = filter_var($_POST['reqDate'], FILTER_SANITIZE_STRING);
$bAddr = filter_var($_POST['_baddr'], FILTER_SANITIZE_STRING);
$bCont = filter_var($_POST['_contact'], FILTER_SANITIZE_STRING);
$bEmail = filter_var($_POST['_email'], FILTER_SANITIZE_STRING);
$bFax = filter_var($_POST['_fax'], FILTER_SANITIZE_STRING);
$bMobile = filter_var($_POST['_mobile'], FILTER_SANITIZE_STRING);
$bPhone = filter_var($_POST['_phone'], FILTER_SANITIZE_STRING);
$dAddr = filter_var($_POST['_daddr'], FILTER_SANITIZE_STRING);
$dCont = filter_var($_POST['_dContact'], FILTER_SANITIZE_STRING);
$bEmail = filter_var($_POST['_dEmail'], FILTER_SANITIZE_STRING);
$bMobile = filter_var($_POST['_dMobile'], FILTER_SANITIZE_STRING);
$bPhone = filter_var($_POST['_dPhone'], FILTER_SANITIZE_STRING);
$notes = filter_var($_POST['_delNotes'], FILTER_SANITIZE_STRING);
$servername = "localhost";
$database = "edwardm3_generation";
$username = "edwardm3_gen";
$password = "*********";
$sql = "mysql:host=$servername;dbname=$database;";
$dsn_Options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
//
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$my_Db_Connection = new PDO($sql, $username, $password, $dsn_Options);
echo "Connected successfully";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
$sql2 = "INSERT INTO orders (custId, orderDate, reqDate, bAddr, bCont, bFax, bMobile, bPhone, dAddr, dCont, dEmail, dMobile, dPhone, notes, orderedBy) VALUES (:custId, :ordDate, :reqDate, :bAddr, :bCont, :bFax, :bMobile, :bPhone, :dAddr, :dCont, :dEmail, :dMobile, :dPhone, :notes, :id)";
$stmt = $my_Db_Connection->prepare($sql2);
$stmt ->bindParam(':custId', $custId, PDO::PARAM_INT);
$stmt ->bindParam(':ordDate', $ordDate, PDO::PARAM_STR);
$stmt ->bindParam(':reqDate', $reqDate, PDO::PARAM_STR);
$stmt ->bindParam(':bAddr', $bAddr, PDO::PARAM_STR);
$stmt ->bindParam(':bCont', $bCont, PDO::PARAM_STR);
$stmt ->bindParam(':bFax', $bFax, PDO::PARAM_STR);
$stmt ->bindParam(':bMobile', $bMobile, PDO::PARAM_STR);
$stmt ->bindParam(':bPhone', $bPhone, PDO::PARAM_STR);
$stmt ->bindParam(':dAddr', $dAddr, PDO::PARAM_STR);
$stmt ->bindParam(':dCont', $dCont, PDO::PARAM_STR);
$stmt ->bindParam(':dEmail', $dEmail, PDO::PARAM_STR);
$stmt ->bindParam(':dMobile', $dMobile, PDO::PARAM_STR);
$stmt ->bindParam(':dPhone', $dPhone, PDO::PARAM_STR);
$stmt ->bindParam(':notes', $notes, PDO::PARAM_STR);
$stmt ->bindParam(':create', $create, PDO::PARAM_INT);
if ($stmt ->execute()) {
echo "New record created successfully";
} else {
echo "Unable to create record";
}
?>

Related

Updating data. Error: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

I want to update the login user profile. When i clicked the update button, this error apprear. Error: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens. May I know why and how to solve it?
This is for updating the users' data
pelanggan_crud.php
<?php
include_once 'database.php';
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Create
if (isset($_POST['create'])) {
try {
$stmt = $conn->prepare("INSERT INTO tbl_pelanggan(pelanggan_id, nama_penuh, nama_pengguna, katalaluan, alamat_pelanggan, email_pelanggan, notel_pelanggan, img) VALUES(:pid, :name, :nama, :password, :alamat, :email, :notel, :img)");
$stmt->bindParam(':pid', $pid, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':nama', $nama, PDO::PARAM_STR);
$stmt->bindParam(':password', $pass, PDO::PARAM_STR);
$stmt->bindParam(':alamat', $alamat, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':notel', $notel, PDO::PARAM_STR);
$stmt->bindParam(':img', $img, PDO::PARAM_STR);
$pid = uniqid('P', true);
$name = $_POST['name'];
$nama = $_POST['nama'];
$pass = md5($_POST['password']);
$repass = md5($_POST['repassword']);
$alamat = $_POST['alamat'];
$email = $_POST['email'];
$notel = $_POST['notel'];
$img = $_POST['img'];
if($pass == $repass) {
echo "<script>alert('Data anda berjaya direkodkan. Terima kasih. Sila log masuk semula')</script>";
$stmt->execute();
}
if($pass !== $repass) {
echo "<script>alert('Pastikan katalaluan dan taip semula katalaluan adalah sama')</script>";
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
//Update
if (isset($_POST['update'])) {
try {
$stmt = $conn->prepare("UPDATE tbl_pelanggan SET nama_penuh = : name, nama_pengguna = :nama, katalaluan = :password, alamat_pelanggan = :alamat, email_pelanggan = :email, notel_pelanggan = :notel, img = :img
WHERE pelanggan_id = :pid");
$stmt->bindParam(':pid', $pid, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':nama', $nama, PDO::PARAM_STR);
$stmt->bindParam(':password', $pass, PDO::PARAM_STR);
$stmt->bindParam(':alamat', $alamat, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':notel', $notel, PDO::PARAM_STR);
$stmt->bindParam(':img', $img, PDO::PARAM_STR);
$pid = $_POST['pid'];
$name = $_POST['name'];
$nama = $_POST['nama'];
$pass = md5($_POST['password']);
$repass = md5($_POST['repassword']);
$alamat = $_POST['alamat'];
$email = $_POST['email'];
$notel = $_POST['notel'];
$img = $_POST['img'];
if($pass == $repass) {
echo "<script>alert('Data anda berjaya dikemas kini. Terima kasih! ')</script>";
$stmt->execute();
header("Location: profil.php");
}
if($pass !== $repass) {
echo "<script>alert('Pastikan katalaluan dan taip semula katalaluan adalah sama!')</script>";
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
//Delete
if (isset($_GET['delete'])) {
try {
$stmt = $conn->prepare("DELETE FROM tbl_pelanggan where pelanggan_id = :pid");
$stmt->bindParam(':pid', $pid, PDO::PARAM_STR);
$pid = $_GET['delete'];
$stmt->execute();
header("Location: mainpelanggan.php");
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
}
//Edit
if (isset($_GET['edit'])) {
try {
$stmt = $conn->prepare("SELECT * FROM tbl_pelanggan where pelanggan_id = :pid");
$stmt->bindParam(':pid', $pid, PDO::PARAM_STR);
$pid = $_GET['edit'];
$stmt->execute();
$editrow = $stmt->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
}
$conn = null;
?>
How can I solve it? Thank you for your time and answer

Uncaught exception 'PDOException' error in my pdo

after running my code i got this kind of error, can anyone help me fix it please. The error starts after putting a code to filter if the email is duplicate or not in the database.
here is the error i got:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = #$_POST['name'];
$age = #$_POST['age'];
$address = #$_POST['address'];
$gender = #$_POST['gender'];
$email = #$_POST['email'];
$dupesql = "SELECT * FROM students WHERE email = :email ";
$dupesql = $dbc->prepare($dupesql);
$dupesql->bindParam(':name', $email);
$dupesql->execute();
$num_rows = $dupesql->rowCount();
if($num_rows === 0)
{
echo "1";
$q = "INSERT INTO students(name, age, address, gender, email ) VALUES(:name, :age, :address, :gender, :email)";
$query = $dbc->prepare($q);
$query->bindParam(':name', $name);
$query->bindParam(':age', $age);
$query->bindParam(':address', $address);
$query->bindParam(':gender', $gender);
$query->bindParam(':email', $email);
$results = $query->execute();
}else{
echo "0";
exit;
}
?>
Well you are facing this error because you are using a wrong parameter in your query.
$dupesql->bindParam(':name', $email);
:name doesn't exists so it should :email.

How to put a condition in my pdo code

I want to do is when a user successfully registered my pdo will have a condition if its successful or not.
My problem how to put a if else condition in pdo if the user is successful or not in registering an account.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = #$_POST['name'];
$age = #$_POST['age'];
$address = #$_POST['address'];
$gender = #$_POST['gender'];
$imageName = #$_FILES['image']['name'];
$q = "INSERT INTO students(name, age, address, gender, imageName ) VALUES(:name, :age, :address, :gender, :image)";
$query = $dbc->prepare($q);
$query->bindParam(':name', $name);
$query->bindParam(':age', $age);
$query->bindParam(':address', $address);
$query->bindParam(':gender', $gender);
$query->bindParam(':image', $imageName);
$results = $query->execute();
?>
My problem how to put a if else condition in pdo if the user is successful or not in registering an account.
PDOStatement::execute() returns boolean true or false depending on the result.
You should be able to check $results for the results...
echo $results ? 'User successfully registered' : 'Error registering user!';

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!";
}

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