Inserting data with PDO. I have tried so many ways and failed - php

I have just begun learning PDO. I have connected to my database and I have a working login happening with the mySql database. Now I am trying to get three pieces of data from a form and then insert them into the table. I have been on this for a week and every version I come up with fails. I get no error messages yet when I check the table it remains empty.
As I have other PDO action working, I'm confident that the problem is in the following piece of code. The button involved is named 'addGig'. This is the first time I have used the name of a button... I'm not confident with this.
I have just edited this post to include my revised code.
So many rookie mistakes!
$date = $_POST['date'];
$venue = $_POST['venue'];
$time = $_POST['time'];
if (!empty($date) && !empty($venue) && !empty($time)){
try{
$query = $connect->prepare("INSERT INTO gigs (date, venue, time) VALUES (:date, :venue, :time)");
$query->bindParam(':date' , $date);
$query->bindParam(':venue' , $venue);
$query->bindParam(':time' , $time);
$query->execute();
}
catch(PDOException $e)
{
handle_sql_errors($query, $e->getMessage());
}
}
}
This is my html form
<form>
<label>date</label><br><input type="text" name="date"><br>
<label>venue</label><br><input type="text" name="venue"><br>
<label>time</label><br><input type="text" name="time"><br>
<br>
<button type="submit" value="addGig" name="addGig">add gig</button>
</form>

You have ZERO error handling, and are simply assuming that your prepare could never fail. If you had error handling, you'd have been told about your syntax errors:
INSERT INTO gigs ('date', 'venue', 'time')
^----^--^-----^--^----^----
You've used the incorrect quotes. ' turns things into string literals. You cannot use string literals as identifiers in MySQL. Identifiers (table/field names) must either be bare words, or quoted with backticks. Since none of your field names are reserved words, backticks are not required. But either of the following would be acceptable
INSERT INTO gigs (`date`, `venue`, `time`)
INSERT INTO gigs (date, venue, time)

you have to edit your prepared statement into the right format:
the columns in your database shouldn't be escaped with '.
"INSERT INTO gigs (date, venue, time) ...
you can write the prepared statement like this (for better reading):
...VALUES (:date, :venue, :time)...
In your bindParam Method you can assign your variables like this:
$query->bindParam(':date' , $date);
Or you do it like in your query:
...VALUES (?, ?, ?)...
and then:
$query->bindParam(1 , $date);
try this:
$query = $connect->prepare("INSERT INTO gigs (date, venue, time) VALUES (:date, :venue, :time)");
$query->bindParam(':date' , $date);
$query->bindParam(':venue' , $venue);
$query->bindParam(':time' , $time);
$query->execute();
for more information consult the manual:
http://php.net/pdo.prepared-statements

There are a few issues here. (Now known after you posted your form code).
One of which is, that you are using <form> which defaults to GET when a method is not given. This in conjunction with your $_POST variables.
Therefore you need to give it a specific method, POST.
<form method="post">
Plus, without an action, defaults to self.
If you're using the form seperately from your SQL, you need to specify it.
I.e.:
<form method="post" action="handler.php">
Plus, you are/were using quotes for your columns. Remove them or using ticks.
Those aren't the right identifiers, as per your original question
https://stackoverflow.com/revisions/28091236/2
('date', 'venue', 'time')
http://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html

Related

Failed to add record to database

I'm sitting with this code for about 2 hours and I still dont know why it isnt working. Check this:
mysql_query("INSERT INTO newsy (tytul, skrot, opis, cena, opinia, galeria, data_utw, extra, kategoria, wartosc_extra, jednostka, stan_magazynowy) VALUES ($tytul, $autor, $skrot, $opis, $data, $extra, $kategoria, $wartosc_extra, $jednostka, $stan_magazynowy)");
Every variable is correctlly passed and I can check all with echo, so the problem is here but I dont know exactly where. Thanks for your help
You're probably inserting strings, and have forgotten to quote them, e.g.
INSERT INTO newsy (tytul, ...) VALUES ('$tytul', ....)
^-- ^---
assuming you're using the deprecated mysql_*() functions, you would have noticed this if you had any sort of error handling on your queries:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
Seems like you have 12 columns in (tytul, skrot, opis, cena, opinia, galeria, data_utw, extra, kategoria, wartosc_extra, jednostka, stan_magazynowy) and you are trying to insert only 10 values.
you are missing quotes around your variables, please change to this
mysql_query("INSERT INTO newsy (tytul, skrot, opis, cena, opinia, galeria, data_utw, extra, kategoria, wartosc_extra, jednostka, stan_magazynowy) VALUES ( '".$tytul."', '".$autor."', '". $skrot."', '".$opis."', '".$data."', '".$extra."', '".$kategoria."', '".$wartosc_extra."', '".$jednostka."', '". $stan_magazynowy."')");
The query will fail anyway since there are 12 fields and 10 variables to insert
Then I would like you to remember that mysql_* functions are deprecated so i would advise you to switch to mysqli or PDO
First pass 12 value instead of 10
and surround value with single quote(') like '$tytul'

Insert multiple same named fields into MySQL Database using PHP

I have multiple fields with names that look like name_$i and I am trying to figure out a way to "on submit", send them all to the database. The thing is that the form is looped and the insert has to be able to adapt to the number of fields in the form. Is there a way to do this???
<?php
$fldcnt = $_POST['fldcnt'];
$i = $_POST['i'];
for ($i = 0; $i < $fldcnt; $i++){
$NAME = $_POST['name_$i'];
$AGE = $_POST['age_$i'];
$ADDRESS = $_POST['address_$i'];
$TELEPHONE = $_POST['telephone_$i'];
$EMAIL = $_POST['email_$i'];
$q_register_new_users = "insert into registration set
NAME = '$NAME',
AGE = '$AGE',
ADDRESS = '$ADDRESS',
TELEPHONE = '$TELEPHONE',
EMAIL = '$EMAIL'";
mysql_query($q_new_products,$connection) or die(mysql_error());
};
?>"
HTML and PHP
You can enter input fields into an array by simply calling the field name[]. Like so:
<input name="name[]" />
You can then use PHP to loop through the fields like so:
foreach($_POST['name'] as $key=>$value){
// Insert the value of the form field into a string or query
// i.e. build the query
$query .= $value;
}
// Then execute the query for each set of fields
The logic above is actually incorrect, but it should give you an idea of what I mean.
MySQL
Your SQL syntax is incorrect, the correct syntax for inserting into a MySQL database is:
INSERT INTO `table` (`field_1`, `field_2`)
VALUES ('value_1', 'value_2')
PLEASE NOTE
The use of the mysql_ functions is hugely discouraged due to there impending deprecation. Instead, most PHP programmers are now using the PDO / SQLite Classes. Whilst these might seem complex, they are actually pretty simple and offer a much more secure way of executing SQL statements.
PDO
SQLite
The syntax for INSERT statement should be like this,
INSERT INTO registration (NAME , AGE , ADDRESS, TELEPHONE, EMAIL)
VALUES ('$NAME', '$AGE', '$ADDRESS','$TELEPHONE', '$EMAIL')
but hte query above is vulnerable with SQL INJECTION, please read the article below to learn how to protect from it,
How can I prevent SQL injection in PHP?
If you are going to keep structure of your code, you need to use double quotes instead of apostrophes
$NAME = $_POST["name_$i"];
or put the variable out
$NAME = $_POST['name_'.$i];
Using array is best way to do this. But if you still want to go head with a counter then you could use
for($i = 0;isset($_POST["name_{$i}"]);$i++)
{
// name found
}
Please note that this code may not be optimal if the name_xx fields are coming from checkboxes, where a user selected items and skipped some in between.
PS. I posted this a comment but it is more suitable as an answer.

Unknown Column in 'field list'

The following code is responsible for the MySQL error Error In Insert-->Unknown column 'expert manager' in 'field list'. If I remove the code below it will solve the MySQL error. Do you know what's wrong with this piece of code?
$l=0;
$source = 'expertmanager';
mysql_query("DELETE FROM `student_questions` WHERE user_id=".$userId."");
for($i=0; $i < $count; $i++)
{
mysql_query("INSERT INTO `student_questions` (`user_id`, `checked_id`, `category_id`, course_id, `question`, `exe_order`, `time`,course_code, year, school, status, close, source) VALUES ('".$userId."', '".$_POST['checkbox'][$i]."', ".$this->cat.", ".$course_id.",'".$_SESSION['question']."','".(++$l)."', '".$time."', '".$course_code."', '".$year."', '".$school."', 1, ".$close.", ".$source.")") or die("Error In Insert-->".mysql_error());
}
Thanks!
What is wrong with this piece of code:
Too short variable names
Don't use variable names that are shorter than 3-5 chars. Every variable name should describe the value(s) you want to store inside.
//bad
$l=0;
//good
$executionOrder = 0;
Concatenation of queries
Don't concatenate queries, it's a bad practice that leads to errors, insecure applications, etc. Don't use the mysql API either, it's outdated, insecure and will be deprecated. Use PDO and prepared statements instead.
//bad
mysql_query("DELETE FROM `student_questions` WHERE user_id=".$userId."");
//good
$statement = $db->prepare("DELETE FROM `student_questions` WHERE user_id = ?);
$statement->execute(array($userId));
Usage of die()
I see it all the time, and I see people telling other people to do that all the time. It's plain simply bad practice and it's time that people start to understand this. You cannot catch the error in any way. You cannot log the error. You cannot control whether it should be output to the screen or not. It's okay to do that in a development environment, but certainly not in a production environment.
You're vulnerable to SQL injection attacks
NEVER, NEVER include user data (session, get, post, cookie, etc.) unfiltered/unescaped into your queries.
//really bad
$query = "SELECT something FROM table WHERE " . $_POST['someValue'];
//better
$query = "SELECT something FROM table WHERE " . mysql_real_escape_string($_POST['someValue']);
//even better: use prepared statements as shown above
And finally the smallest thing that's wrong and the one that created your error
//bad
$query = "INSERT INTO `student_questions` (source) VALUES (expertmanager)"; //that's what you have
//better
$query = "INSERT INTO `student_questions` (source) VALUES ('expertmanager')";
Do you have a column called expert manager? If so, try changing the name to 'expert_manager' (without quotes), and see if that works.
You forgot quotes around several values in your insert statement :
for($i=0; $i < $count; $i++)
{
mysql_query("INSERT INTO `student_questions` (`user_id`, `checked_id`, `category_id`, course_id, `question`, `exe_order`, `time`,course_code, year, school, status, close, source) VALUES ('".$userId."', '".$_POST['checkbox'][$i]."', '".$this->cat."', '".$course_id."','".$_SESSION['question']."','".(++$l)."', '".$time."', '".$course_code."', '".$year."', '".$school."', 1, '".$close."', '".$source."')") or die("Error In Insert-->".mysql_error());
}
Not only $source, there are also : $course_id, $close, etc.
You have not enclosed the value of $source (which is the string expert_manager) in single quotes in your query.
mysql_query("INSERT INTO `student_questions` (...snip...) VALUES (...snip...'".$school."', 1, ".$close.", '".$source."')") or die("Error In Insert-->".mysql_error());
//------------------------------------------------------------------------------------------------------^^^^^^^^^^^^^^^^
We cannot see the value of $close, but if it is a string value rather than numeric, it should probably be enclosed in quotes as well.
Additional note: I see $_POST['checkbox'][$i] passed directly into the query. Please make sure this input has been properly validated and escaped with mysql_real_escape_string() if necessary. The same rule may apply to other variables used in the VALUES() list, but we cannot see their origins with the code posted.

Inserting date value into MySQL

I currently have a form which takes a date in the format m/d/y - I have then attempted to insert it into a table, but the value in the table reads 0000-00-00. I understand that the value is not being inserted due to the format of the date being inserted.
The problem is, I am unsure on how to change the format so that it is inserted in a format that MySQL will store.
Below is the function that inserts the data into the table:
public function addUser($array) {
$array['password'] = $this->hashPassword($array['password']);
$implodeArray = '"'.implode( '","', $array ).'"';
$sql = ('INSERT INTO user
(email, password, firstName, lastName, officeID, departmentID, managerID, roleID, username, contractType, startDate, endDate, totalLeaveEntitlement, remainingLeave)
VALUES
('.$implodeArray.')');
echo $sql;
die();
mysql_query($sql,$this->_db) or die(mysql_error());
mysql_close();
}
Due to the use of implodeArray, I cannot format the value of startDate and endDate to match the MySQL DATE format.
Why don't you use similar method to when you hashed the password? So, you just need to add another function to convert your date input into mysql date format:
public function addUser($array) {
$array['password'] = $this->hashPassword($array['password']);
$array['startDate'] = $this->mysql_date_format($array['startDate']);
$array['endDate'] = $this->mysql_date_format($array['endDate']);
$implodeArray = '"'.implode( '","', $array ).'"';
$sql = ('INSERT INTO user (email, password, firstName, lastName, officeID, departmentID, managerID, roleID, username, contractType, startDate, endDate, totalLeaveEntitlement, remainingLeave) VALUES ('.$implodeArray.')');
echo $sql;
die();
mysql_query($sql,$this->_db) or die(mysql_error());
mysql_close();
}
Hmmmmm
I know it looks like its easier to write queries like this (one function generates all your parameters etc etc) but I would STRONGLY advise that you prepare your statements - someone coming along to support your code will thank you for it.
That way you can use NOW(), DATE_DIFF and such other awesomes...
I know that doesn't answer your question but I do feel you should take the time to construct your queries properly - help prevent run time errors/ attacks etc etc.
Not sure on the specifics of your issue, but in general:
$mysql_formatted_date = date("Y-m-d", strtotime($mdy_formatted_date));
I think you'll want STR_TO_DATE()
STR_TO_DATE("%m/%d/%Y") is I think the right format
While both arrays and mysql columns have an implicit order, how do you know they are the same?
It would have been a lot more useful if you'd provided the output of 'echo $sql' rather than all the PHP code - although hte latter highlights a lot of messy programming not least:
the field order problem
quoting non-numeric values
not escaping fields properly
not trapping / handling errors
no comments
form which takes a date in the format m/d/y - I have then attempted to insert it
In the case of date fields, quoting is optional depending on the format used for the literal - but it is always ordered as per ISO 8601 - i.e. big endian
public function addUser($array) {
list($d,$m,$y) = explode("/",$array['startDate']);
$array['startDate'] = "$y-$m-$d";
list($d,$m,$y) = explode("/",$array['endDate']);
$array['endDate'] = "$y-$m-$d";
$array['password'] = $this->hashPassword($array['password']);
foreach($array as $key => $value){
$array[$key] = mysql_real_escape_string($value);
}
$implodeArray = implode("','", $array);
$sql = "INSERT INTO user VALUES (NULL,'$implodeArray')";
echo $sql;
die();
mysql_query($sql,$this->_db) or trigger_error(mysql_error());
}

Issue with Inserting a record into a MySql database

I am having an issue with a simple form uploading script.
On this upload script I built to upload data to a MySql database, I can't seem to get the record to insert into the database when I include this one variable.
I figured that perhaps I am overlooking some minor coding issue, and I'm working on a deadline to get this system live...
Here is the code snippit that is giving me issues.
$title=$_REQUEST['title'];
$author=$_REQUEST['author'];
$hours=$_REQUEST['hours'];
$start_d=$_REQUEST['start_d'];
$start_m=$_REQUEST['start_m'];
$start_y=$_REQUEST['start_y'];
$end_d=$_REQUEST['end_d'];
$end_m=$_REQUEST['end_m'];
$end_y=$_REQUEST['end_y'];
$certificate=$_REQUEST['certificate'];
$required=$_REQUEST['required'];
$assessment=$_REQUEST['assessment'];
$describe=$_REQUEST['description'];
$query=mysql_query("INSERT INTO `records` (title, hours, start_date_d, start_date_m, start_date_y , end_date_d, end_date_m, end_date_y , certificate, requirement, author, approved, assessment, describe) VALUES ('$title', '$hours', '$start_d', '$start_m', '$start_y', '$end_d', '$end_m', '$end_y', '$certificate', '$required', '$author', '0', '$assessment', '$describe')");
mysql_close();
The variable that is giving me issues is the one denoted as '$describe'.
My previous testing has indicated:
The form script is collecting data correctly
The form script is passing the data to the upload script correctly via method='post'
The database connection information is correct
All of the field names in the mysql query are typed correctly
Thank you in advance for your help.
Update:
echo mysql_error(); => "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' assessment, describe) VALUES' at line 1
this awful code should be totally rewritten.
but to solve this very problem
foreach ($_REQUEST as $key => $value) $_REQUEST[$key] = mysql_real_escape_string($value);
Something like this.
Note that i've changed date fields to date format.
$_POST['start_date'] = $_POST['start_y'].'-'.$_POST['start_m'].'-'.$_POST['start_d'];
$_POST['end_date'] = $_POST['end_y'].'-'.$_POST['end_m'].'-'.$_POST['end_d'];
$_POST['approved'] = 0;
$fields = explode(" ","title author hours start_date end_date certificate required assessment describe");
$query = "INSERT INTO `records` SET ".dbSet($fields);
mysql_query($query) or trigger_error(mysql_error().$query);
function dbSet($fields) {
$q='';
foreach ($fields as $v) $q.="`$v`='".mysql_real_escape_string($_POST[$v])."', ";
return trim($q,", ");
}
Try this:
$query="INSERT INTO `records` (title, hours, start_date_d, start_date_m, start_date_y , end_date_d, end_date_m, end_date_y , certificate, requirement, author, approved, assessment, describe) VALUES ('$title', '$hours', '$start_d', '$start_m', '$start_y', '$end_d', '$end_m', '$end_y', '$certificate', '$required', '$author', '0', '$assessment', '$describe')";
var_dump($query);
And post to us :)
It turns out that "Describe" is a reserved word in MySql.
I changed the field name, and now my script works...

Categories