SQL Query using PHP PDO - php

I'm trying to create a SQL query using PHP in which it checks to see if a row has already been submitted/set using the same date and user name. If it hasn't it inserts a new row. If it does find a match, it updates the row instead.
I can insert a new row fine, but when I use a pre-existing date and name, I receive no error in any of my logs, and the query appears to run without any problems. But when checking the database, I notice that there are no UPDATES actually set to the row. When I run the update command manually in SQL, it appears to work fine.
Having no logs/error data to go on, I was hoping to get some advice here. I'm sure there must be something I'm missing here. This is what I'm currently using:
require_once 'db-conn.php';
$name = $_POST['name'];
$email = $_POST['email'];
$date = $_POST['date'];
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
$var4 = $_POST['var4'];
$conn = db_connect ();
$sqlq = "SELECT * FROM tbl WHERE date = '$date' AND name = '$name'";
$nRows = $conn->query("$sqlq")->fetchColumn();
if ($nRows==0) {
try {
$sqli = "INSERT INTO tbl (name,email,date,var1,var2,var3,var4) VALUES (:name,:email,:date,:var1,:var2,:var3,:var4)";
$sql = $conn->prepare("$sqli");
$sql->execute(array(':name' => $name, ':email' => $email, ':date' => $date, ':var1' => $var1, ':var2' => $var2, ':var3' => $var3 ':var4' => $var4));
} catch(PDOException $e) {
die ('SQL Error');
}
}
else {
try {
$sqli = "UPDATE tbl SET email='$email', notes='$notes', var1='$var1', var2='$var2', var3='$var3' WHERE date='$date' AND name='$name'";
$sql = $conn->prepare("$sqli");
$sql->execute(array($name, $email, $date, $var1, $var2, $var3, $var4));
} catch(PDOException $e) {
die ('SQL Error');
}
}

You don't have the bound variables correct:
$sqli = "UPDATE tbl SET email=:email, notes=:notes, var1=:var1, var2=:var2, var3=:var3 WHERE date=:date AND name=:name";
$sql = $conn->prepare("$sqli");
$sql->execute(array(':name' => $name, ':email' => $email, ':date' => $date, ':var1' => $var1, ':var2' => $var2, ':var3' => $var3, ':notes'=>$notes));
You did it correct in the Insert statement but not in the update.
Not sure where you are getting $notes from though.
Plus not sure if it is intentional or not but you are not updating var4 in the update query.

Related

php- inserting data into the database

I am a beginner when we talk about PHP. SO I have no idea where I made a mistake using PHP.
<?php
require "conn.php";
$name = "yolo";
$surname = "yolo";
$nameOfFee= "asd";
$date = '2012-08-06';
$mysql_query = "(INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee)
SELECT Person.ID,Fee.ID,'$date'
FROM Person,Fee
WHERE Person.Name = '$name' AND Person.Surname = '$surname' AND Fee.Name_of_fee = '$nameOfFee');";
if($conn->query($mysql_query) === TRUE){
echo "Insert completed";
}
else{
echo "Insert not completed";
}
$conn->close();
?>
It always puts that Insert is not complete...
The Problems
There are a few syntax errors in this piece of code you have provided:
// here it starts, what is this "(" for before insert?
// Take note that your query is vulnerable to SQL attacks
$mysql_query = "(INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee)
SELECT Person.ID,Fee.ID,'$date'
FROM Person,Fee
WHERE Person.Name = '$name' AND Person.Surname = '$surname' AND Fee.Name_of_fee = '$nameOfFee');";
How to fix it
To fix these things I recommend you use the MySQLi OOP, like you are using now, but add prepared statements. I will walk through the new code with you so you can understand the process.
require "conn.php";
$name = "yolo";
$surname = "yolo";
$nameOfFee= "asd";
$date = '2012-08-06';
$sql = "INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee) VALUES (?, ?, ?)"; // rewrite your query with a preset number of values to prevent SQL Attacks
if($stmt = $conn->prepare( $sql ))
{ // before we run check to make sure the query worked
$stmt->bind_param('sss', $name, $nameOfFee, $date); // bind your variables so to know what goes where
$stmt->execute(); // execute the query
$stmt->close(); // close connection for safety
// message as an array for the user as feedback.
$message = array(
'is_error' => 'success',
'message' => 'Record was entered into database.'
);
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Query Error, please revise the information.'
);
}

invalid parameter number exception using named parameter

I am getting "invalid parameter number:parameter undefined" exception when attempting an insert query to mysql database.
I am returning the result to my Android app as json.
if (!empty($_POST))
{
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:fromm,:too,:ccode,:stud,:rmk ) ";
$query_params = array(
':dat' => $_POST['datee'],
':from'=>$_POST['fromm'],
':to'=>$_POST['too'],
':ccode'=>$_POST['course'],
':stud'=>$_POST['sname'],
':rmk'=>$_POST['remark'],
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
$response["date"] = $_POST['datee'];
$response["from"] = $_POST['fromm'];
$response["to"] = $_POST['too'];
$response["ccode"] = $_POST['course'];
$response["stud"] = $_POST['sname'];
$response["remark"] = $_POST['remark'];
die(json_encode($response));
}
}
you lack a m in
':from'=>$_POST['fromm'],
should be
':fromm'=>$_POST['fromm'],
you must be careful when using named parameter, I myself am very prone to making such errors
that's why I more easily use the ? placeholder, this way in your exemple:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (?,?,?,?,?,?) ";
$query_params = array(
$_POST['datee'],
$_POST['fromm'],
$_POST['too'],
$_POST['course'],
$_POST['sname'],
$_POST['remark'],
);
then:
$result = $stmt->execute($query_params);
you must be sure that the params are in good order (same as in query)
In your query, you're misspelling from:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:fromm,:too,:ccode,:stud,:rmk ) ";
Replace it with:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:from,:too,:ccode,:stud,:rmk ) ";

not getting any results!! is there an error with the pdo code?

The code is not giving any result can you help me ?
$f_name = $_POST['first_name'];
$l_name = $_POST['last_name'];
$e_mail = $_POST['email'];
$sql = "INSERT INTO
informations(first name, last name,email ,email)
VALUES($f_name,$l_name,$e_mail)";
/*$result = pdo::query($sql);
if(!$result)*/
$result = $sql->fetch(PDO::FETCH_ASSOC);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while registering. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
echo 'Successfully registered. You can now sign in and start posting! :-)';
}
You currently aren't using PDO propertly, you're fetching results with an insert query, and you aren't making the most of parameter binding.
Try this:
// make sure $db is initialized as a new PDO object
// use :param placeholders for binding
$sql = "INSERT INTO informations(first name, last name, email) VALUES(:first, :last, :email)";
// prepare query
$query = $db->prepare($sql);
// set up parameter binding replacements
$binding = array(
':first' => $f_name,
':last' => $l_name,
':email' => $e_mail // strange variable name splitting...
);
// execute the query (returns boolean true or false)
$query_results = $query->execute($binding);
// process result message
if($query_results) {
echo 'Success';
} else {
echo 'Something went wrong! Error: ' . $query->errorInfo();
}
For reference:
PDO::execute() manual
PDO introduction tutorial
Another PDO tutorial

Delete MySQL PHP

mysql_connect('localhost', 'root', '')
or die(mysql_error());
mysql_select_db('shuttle_service_system')
or die(mysql_error());
$insert="INSERT INTO inactive (ID_No, User_Password, First_Name, Last_Name, Email, Contact_Number)
VALUES('". $ID_No ."','". $UserPassword ."','". $FirstName ."','". $LastName ."','". $Email ."','". $ContactNumber ."')";
$result=mysql_query($insert);
$sql="DELETE FROM users WHERE ID_No = '$ID_No'";
$result2=mysql_query($sql);
if($result && $result2){
echo"Successful!";
} else {
echo "&nbsp Error";
}
Hi guys I have been stuck in delete function of MySQL, I have tried searching the net but when I ran my code it always goes to the else part which means there is an error, the insert is already okay but the delete is not.
PHP variables are allowed in double quotes. Hence try this,
$sql="DELETE FROM users WHERE ID_No = $ID_No";
Your first query was not properly escaped. Rewrite like
$insert="INSERT INTO inactive (`ID_No`, `User_Password`, `First_Name`, `Last_Name`, `Email`, `Contact_Number`)
VALUES('$ID_No','$UserPassword','$FirstName','$LastName','$Email','$ContactNumber')";
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
First, use PDO.
Make your connection Database like this:
function connectToDB(){
$host='localhost';
try {
$user = 'username';
$pass = 'password';
$bdd = 'databaseName';
$dns = 'mysql:host='.$host.';dbname='.$bdd.'';
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
return $connexion = new PDO($dns, $user, $pass, $options);
}catch ( Exception $e ) {
echo "Fail to connect: ", $e->getMessage();
die();
}
}
To delete something, here is an example:
function deleteUserWithId($ID_No){
$connexion = connectToDB();
try{
$connexion->exec('DELETE FROM users WHERE ID_No = '.$ID_No);
}catch(Exception $e){
echo "Error: ".$e->getMessage();
}
}
To insert something:
function addInactiveUser($UserPassword,$FirstName ,$LastName ,$Email,$ContactNumber){
$connexion = connectToDB();
$insert = $connexion->prepare('INSERT INTO inactive VALUES(:ID_No,
:User_Password,
:First_Name,
:Last_Name,
:Email,
:Contact_Number
)');
try {
// executing the request
$success = $insert->execute(array(
'ID_No'=>'',
'User_Password'=>$UserPassword,
'First_Name'=>$FirstName ,
'Last_Name'=>$LastName ,
'Email'=>$Email,
'Contact_Number'=>$ContactNumber
));
if($success)
// OK
else
// KO
}
catch (Exception $e){
echo "Error: ".$e->getMessage();
}
}
To make a select:
// If you want to display X user per pages for example
function getAllInactiveUsers($page, $numberInactiveUserPerPage){
$connexion = connectToDB();
$firstInactiveUser = ($page - 1) * $numberInactiveUserPerPage;
$selectAllInactiveUsers = $connexion->prepare('SELECT * FROM inactive ORDER BY ID_No DESC LIMIT '.$firstInactiveUser.','.$numberInactiveUserPerPage);
return $selectAllInactiveUsers ;
}
To get the results of this methods, just do something like this:
$inactiveUsers= getAllInactiveUsers(1,15); // for page 1, display 15 users
$inactiveUsers->execute();
while($row = $inactiveUsers->fetch(PDO::FETCH_OBJ)){
$id = $row->ID_No;
$first_name = $row->First_Name;
// etc...
}
Hope that's help :)
I am not sure if this helps you, but as an alternative you could delete the last entry in the table:
$delQ = mysql_query("SELECT * FROM ph ORDER BY id DESC LIMIT 1" );
while(( $ar = mysql_fetch_array($delQ)) !== false){
mysql_query("DELETE FROM ph WHERE id= $ar[id]");
}

PHP PDO Insert Using Loop

I am having trouble using PDO to insert multiple records into a database. I can successfully add a single record, but as soon as I add the foreach loop, it fails. After reading a number of other SO questions regarding this, I believe I need to "bind" my variables, although I am completely confused on the proper syntax.
Here is the original function I created:
<? function addToDatabase () {
//Get All Variables
$timestamp = date("Y-m-d H:i:s");
$schoolName = $_SESSION['schoolName'];
$schoolStreet = $_SESSION['schoolStreet'];
$schoolCity = $_SESSION['schoolCity'];
$schoolState = $_SESSION['schoolState'];
$schoolZip = $_SESSION['schoolZip'];
$schoolContactName = $_SESSION['schoolContactName'];
$schoolContactTitle = $_SESSION['schoolContactTitle'];
$schoolContactPhone = $_SESSION['schoolContactPhone'];
$schoolCsontactEmail = $_SESSION['schoolContactEmail'];
$inputMethod = $_SESSION['inputMethod'];
$studentDataArray = $_SESSION['studentDataArray'];
$studentFirstNameField = $_SESSION['studentFirstNameField'];
$studentLastNameField = $_SESSION['studentLastNameField'];
$studentStreetField = $_SESSION['studentStreetField'];
$studentCityField = $_SESSION['studentCityField'];
$studentStateField = $_SESSION['studentStateField'];
$studentZipcodeField = $_SESSION['studentZipcodeField'];
$studentDOBField = $_SESSION['studentDOBField'];
$studentGenderField = $_SESSION['studentGenderField'];
$studentGradeField = $_SESSION['studentGradeField'];
//Connnect to Database
$host = 'myHost';
$un = 'myUsername';
$pw = 'myPassword';
$db_name = 'myTable';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbName", $un, $pw);
echo 'Connected to database<br>';
$sql = "INSERT INTO studentData (originallyAddedOn, inputMethod, studentFirst, studentLast, studentStreet, studentCity, studentState, studentZip, studentDOB, studentGender, studentGrade, schoolName, schoolStreet, schoolCity, schoolState, schoolZip, schoolContactName, schoolContactTitle, schoolContactEmail, schoolContactPhone) VALUES (:originallyAddedOn, :inputMethod, :studentFirst, :studentLast, :studentStreet, :studentCity, :studentState, :studentZip, :studentDOB, :studentGender, :studentGrade, :schoolName, :schoolStreet, :schoolCity, :schoolState, :schoolZip, :schoolContactName, :schoolContactTitle, :schoolContactEmail, :schoolContactPhone)";
foreach ($studentDataArray as $student){
$q = $conn->prepare($sql);
echo $student[$studentFirstNameField]."<br>";
$q->execute(array( ':originallyAddedOn'=>$timestamp,
':inputMethod'=>$inputMethod,
':studentFirst'=>$student[$studentFirstNameField],
':studentLast'=>$student[$studentLastNameField],
':studentStreet'=>$student[$studentStreetField],
':studentCity'=>$student[$studentCityField],
':studentState'=>$student[$studentStateField],
':studentZip'=>$student[$studentZipField],
':studentDOB'=>$student[$studentDOBField],
':studentGender'=>$student[$studentGenderField],
':studentGrade'=>$student[$studentGradeField],
':schoolName'=>$schoolName,
':schoolStreet'=>$schoolStreet,
':schoolCity'=>$schoolCity,
':schoolState'=>$schoolState,
':schoolZip'=>$schoolZip,
':schoolContactName'=>$schoolContactName,
':schoolContactTitle'=>$schoolContactTitle,
':schoolContactEmail'=>$schoolContactEmail,
':schoolContactPhone'=>$schoolContactPhone));
}
// close the database connection
$dbh = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
The $studentDataArray looks similar to this:
0 => //student 1
array
[0] => 'Joe' //First
[1] => 'Smith' //Last
[2] => '101 Main St' //Street
[3] => 'Boston' //City
[4] => 'MA' //State
[5] => '01234' //Zip
[6] => '2000-01-01' //Date of Birth
[7] => 'Male' //Gender
[8] => '12' //Grade
1 => //Student 2
array
[0] => 'Jane'
[1] => 'Smith'
[2] => '99 Main St'
[3] => 'Boston'
[4] => 'MA'
[5] => '01234'
[6] => '2000-02-02'
[7] => 'Female'
[8] => '10'
UPDATE: For those that are interested, here is my final function after I fixed the errors:
<? function addToDatabase ($dataArray) {
//Connnect to Database
$host = 'myHost';
$un = 'myUsername';
$pw = 'myPassword';
$db_name = 'myTable';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbName", $un, $pw);
echo 'Connected to database<br>';
$sql = "INSERT INTO studentData (originallyAddedOn, inputMethod, studentFirst, studentLast, studentStreet, studentCity, studentState, studentZip, studentDOB, studentGender, studentGrade, schoolName, schoolStreet, schoolCity, schoolState, schoolZip, schoolContactName, schoolContactTitle, schoolContactEmail, schoolContactPhone) VALUES (:originallyAddedOn, :inputMethod, :studentFirst, :studentLast, :studentStreet, :studentCity, :studentState, :studentZip, :studentDOB, :studentGender, :studentGrade, :schoolName, :schoolStreet, :schoolCity, :schoolState, :schoolZip, :schoolContactName, :schoolContactTitle, :schoolContactEmail, :schoolContactPhone)";
$q = $conn->prepare($sql);
foreach ($dataArray as $student){
$a = array (':originallyAddedOn'=>$student['timestamp'],
':inputMethod'=>$student['inputMethod'],
':studentFirst'=>$student['studentFirst'],
':studentLast'=>$student['studentLast'],
':studentStreet'=>$student['studentStreet'],
':studentCity'=>$student['studentCity'],
':studentState'=>$student['studentState'],
':studentZip'=>$student['studentZip'],
':studentDOB'=>$student['studentDOB'],
':studentGender'=>$student['studentGender'],
':studentGrade'=>$student['studentGrade'],
':schoolName'=>$student['schoolName'],
':schoolStreet'=>$student['schoolStreet'],
':schoolCity'=>$student['schoolCity'],
':schoolState'=>$student['schoolState'],
':schoolZip'=>$student['schoolZip'],
':schoolContactName'=>$student['schoolContactName'],
':schoolContactTitle'=>$student['schoolContactTitle'],
':schoolContactEmail'=>$student['schoolContactEmail'],
':schoolContactPhone'=>$student['schoolContactPhone']);
if ($q->execute($a)) {
// Query succeeded.
} else {
// Query failed.
echo $q->errorCode();
}
// close the database connection
$dbh = null;
echo "Insert Complete!";
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
You dont need to bind your variables. Ive done this before with similar code. Its hard to say whats going wrong though. Do you get an exception - if so what is it?
The only thing i see wrong is you have your preparation inside the loop... should be more like:
try {
$conn = new PDO("mysql:host=$host;dbname=$dbName", $un, $pw);
echo 'Connected to database<br>';
$sql = "INSERT INTO studentData (originallyAddedOn, inputMethod, studentFirst, studentLast, studentStreet, studentCity, studentState, studentZip, studentDOB, studentGender, studentGrade, schoolName, schoolStreet, schoolCity, schoolState, schoolZip, schoolContactName, schoolContactTitle, schoolContactEmail, schoolContactPhone) VALUES (:originallyAddedOn, :inputMethod, :studentFirst, :studentLast, :studentStreet, :studentCity, :studentState, :studentZip, :studentDOB, :studentGender, :studentGrade, :schoolName, :schoolStreet, :schoolCity, :schoolState, :schoolZip, :schoolContactName, :schoolContactTitle, :schoolContactEmail, :schoolContactPhone)";
// prepare once... exceute many :-)
$q = $conn->prepare($sql);
foreach($studentDataArray as $student) {
$q->execute($yourDataArray);
// do other stuff if needed
}
} catch(PDOException $e) {
echo $e->getMessage();
}
For loops, do this (PDO or other database client libraries that support prepared statements):
prepare the SQL INSERT query.
bind the variables.
loop your array against the bind variables, execute once per iteration.
Profit.
For a PDO based example on an array with data to insert into some table that requires a single column named option.
First some data to be inserted into the database:
$options = [
['option' => "Insert Option A " . uniqid()],
['option' => "Insert Option B " . uniqid()],
['option' => "Insert Option C " . uniqid()],
];
Somewhere else, let's assume to have that $options array and care about the database interaction. This needs a connection:
$conn = new PDO('mysql:dbname=test;host=localhost', 'testuser', 'test');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
Now let's prepare the insert query. Using named parameters here like in the question, sure this works with numbered parameters, too:
$stmt = $conn->prepare('INSERT INTO config (`OPTION`) VALUES (:OPTION);');
Now let's bind the named parameter to a variable here. Take note, that the variable is prefixed (here with insert). This is actually the aliasing to the option key in the input array:
$stmt->bindParam(':OPTION', $insert_option);
So now from the numbered list above, the points 1.) prepare the SQL INSERT query. and 2.) bind the variables. has been done.
Only left is the loop over the $options array to insert the values:
foreach ($options as $insert) {
extract($insert, EXTR_PREFIX_ALL, 'insert');
$stmt->execute();
}
Making use of extract allows to set multiple variables at once based on the input array in an aliased fashion without much ado.
The full example:
$options = [
['option' => "Insert Option A " . uniqid()],
['option' => "Insert Option B " . uniqid()],
['option' => "Insert Option C " . uniqid()],
];
$conn = new PDO('mysql:dbname=test;host=localhost', 'testuser', 'test');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
# 1. Prepare
$stmt = $conn->prepare('INSERT INTO config (`OPTION`) VALUES (:OPTION);');
# 2. Bind
$stmt->bindParam(':OPTION', $insert_option);
# 3. Loop & Execute
foreach ($options as $insert) {
extract($insert, EXTR_PREFIX_ALL, 'insert');
$stmt->execute();
}

Categories