Issue with Inserting a record into a MySql database - php

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...

Related

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

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

Error putting data into database

I have the following php code:
foreach($html->find('dl[class=movie-info]') as $info) {
for($i = 0; $i <= 20; $i++) {
$contenido = $info->find('dt',$i)->plaintext;
if($contenido == 'Año'){
$year = utf8_encode($info->find('dd',$i)->plaintext);}}}
(the code has more if functions)
And a mysql table where I put the content of the variables....
The problem is with the $year content, I need to fill it in a smallint(5) unsigned.
When I use
$con = mysqli_connect("localhost","root","tdguchiha","phpbb3");
mysqli_query($con,"INSERT INTO pablo (forum_id, calidad, titulo, caratula, sinopsis, pais, director, reparto, genero) VALUES ('$forum_id', '$calidad', '$titulo', '$img', '$sinopsis', '$pais', '$director', '$reparto', '$genero')");
mysqli_close($con);
All the content is inserted, but when i try to insert $year into año with type smallint(5) unsigned nothing happens, no row is created...
how can I convert $year to a number (it must be a number) to fill it in that column? or I need to change the column type?
PD: I am learning right now to "play" with mysql
thanks
There is no difference in mysql between a number and a string when doing queries. Make sure you include the column name in the list of all the columns:
mysqli_query($con,"INSERT INTO pablo (forum_id, calidad, titulo, caratula, sinopsis, pais, director, reparto, genero, year) VALUES ('$forum_id', '$calidad', '$titulo', '$img', '$sinopsis', '$pais', '$director', '$reparto', '$genero', '$year')");
^notice year the column ^now the actual value
Just replace year in the column section with the name of your mysql column.
Perhaps try casting it to an integer instead of using utf8_encode:
$year = intval($info->find('dd',$i)->plaintext);
Or, in addition to it:
$year = intval(utf8_encode($info->find('dd',$i)->plaintext));
Can you give us an example of the data?
EDIT: Damien is right, intval() shouldn't make a difference.
Try echoing out the contents instead, and making sure it's an actual number in the string to do some debugging:
if($contenido == 'Año'){
$year = utf8_encode($info->find('dd',$i)->plaintext);
echo $year.'<br />';}}}
Before posting a question to StackOverflow, identify any error-codes / error-messages and post them with your question:
/* check connection */
if ( mysqli_connect_errno() ) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
And:
if ( ! mysqli_query( $link, "SELECT ..." )) {
printf("Errorcode: %d\n", mysqli_errno($link));
}
More on the PHP doc site.
I think your problem is with value type and data you are trying to insert:
A smallint is between -32768 and 32767 signed, or 0 and 65535 unsigned.
The (5) represents the display width of the field - if you will try to put 90000 you will be rejected.
In your case it should not be a problem (years value I assume) but show us the data you are trying to insert.
I guess that you are parsing some content using simple_html_dom - make sure all data retrieved is
as you expect before inserting it to DB.
Also: Try changing the type to int(5) and now tell us....
It will be easier to see the query you use (with the year) and a sample of data.
For error loging and display use:
$execute = mysqli_query($con,"INSERT INTO pablo ( ....your query..... ")
or
printf("Errormessage: %s\n", mysqli_error($con));
Have Fun

How to properly INSERT INTO MySQL Using PHP Variables

I'm having a problem with my personal server where I'm trying to create a database for the decade old binders I have for the Yu-Gi-Oh! Trading Card Game (haven't played in years). In testing the INSERT INTO, I keep running across a particular problem...
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 ''Magic'(Name, Description, Card_ID, Pack, P_ID, Quantity) VALUES ('Post', 'Post ' at line 1
Now my code outputs properly when I comment out the query function and echo to my webpage, but I keep getting the above mysql_error() message being displayed.
My code snippet is as follows...
if(isset($_SESSION['username'])) {
mysql_connect("localhost", "my_username", "my_password") or die(mysql_error());
mysql_select_db("my_db") or die(mysql_error());
function clean_string($value) {
if(get_magic_quotes_gpc() ) {
$value = stripslashes($value);
}
return mysql_real_escape_string($value);
}
$Show = clean_string($_POST['show']);
$Table = clean_string($_POST['table']);
$Insert_M_T = $_POST['insert_magic_traps'];
$Insert_Monster = $_POST['insert_monster_effect'];
$Insert_Card_Type = clean_string($_POST['I_Type']);
$Insert_Card_Name = clean_string($_POST['I_Card_Name']);
$Insert_Description = clean_string($_POST['I_C_Description']);
$Insert_Card_ID = clean_string($_POST['I_Card_ID']);
$Insert_CardPack = clean_string($_POST['I_C_Pack']);
$Insert_PackID = clean_string($_POST['I_C_P_ID']);
$Insert_Quantity = clean_string($_POST['I_C_Quantity']);
if(isset($Insert_M_T)) {
$sql = "INSERT INTO '$Insert_Card_Type'(Name, Description, Card_ID, Pack, P_ID, Quantity) VALUES ('$Insert_Card_Name', '$Insert_Description', '$Insert_Card_ID', '$Insert_CardPack', '$Insert_PackID', '$Insert_Quantity')";
mysql_query($sql) or die(mysql_error());
echo "<center><h2>Record added to Table: $Insert_Card_Type</h2></center>";
echo "<center><table><tr><th>Name:</th><td>$Insert_Card_Name</td></tr><tr><th>Description:</th><td>$Insert_Description</td></tr><tr><th>Card ID:</th><td>$Insert_Card_ID</td></tr><tr><th>Pack:</th><td>$Insert_CardPack</td></tr><tr><th>Pack ID Number</th><td>$Insert_PackID</td></tr><tr><th>Quantity:</th><td>$Insert_Quantity</td></tr></table></center>";
}
?>
//more html and php code
<?php
} else {
echo "<h1><center><font color=#ff0000 >ACCESS DENIED!!!</font></center></h1>";
echo "<h2><center><a href=index.php >Login Here!</a></center></h2>";
}
?>
Any advice would be helpful. I've tried searching for how to get around this problem, but to no avail. I feel like this is a simple fix, but I'm missing it. Please advise.
Thank you in advance.
~DanceLink
INSERT INTO `$Insert_Card_Type` (Name, Description, Card_ID, Pack, P_ID, Quantity)
VALUES ('$Insert_Card_Name', '$Insert_Description', '$Insert_Card_ID', '$Insert_CardPack', '$Insert_PackID', '$Insert_Quantity')
Backticks around $Insert_Card_Type, not single quotes.

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

mysql query insert issue

my query is not inserting and i'm not getting any errors. can't figure out why it's not inserting
foreach($_POST as $key => $value) {
$clean[$key] = mysql_real_escape_string($value);
}
if(isset($_POST['submit'])) {
$entry = "INSERT INTO test (Word, Type, Lang, Country, Gender, Advice, y_Advice, Notes,
EditorNotify, Equiv)
VALUES('".$clean["word_field"]."',
'".$clean["type_field"]."',
'".$clean["lang"]."',
'".$clean["Country"]."',
'".$clean["gender"]."',
'".$clean["advice"]."',
'".$clean["y_advice"]."',
'".$clean["Notes"]."',
'".($clean["Notes"] != '' ? '1' : '')."',
'".$clean["Equiv"]."')";
echo mysql_query ($entry);
mysql_query ($entry);
You're actually doing the insert twice because of this:
echo mysql_query ($entry);
mysql_query ($entry);
The echo line will run the query, and so will the line after it. You need to get rid of that. (though I guess you only put it in there for testing purposes?)
Instead of that, I'd suggest just echoing $entry itself, so you get to see the finished SQL string. You may spot something wrong with the query right away just from that.
If you don't, then try copying+pasting that string into a SQL query program to see what the actual error is. That'll allow you to play with the query until you get it right.
You could also use the PHP command mysql_error() to get the error out of PHP, but it's when you've got a weird SQL error, it can often be quicker and easier to play with the query directly rather than within the PHP code.
hope that helps.
Try replacing:
(Word, Type, Lang, Country, Gender, Advice, y_Advice, Notes,
EditorNotify, Equiv)
With:
(`Word`, `Type`, `Lang`, `Country`,`Gender`, `Advice`, `y_Advice`, `Notes`,
`EditorNotify`, `Equiv`)
You don't know whether you're getting any errors. First, get rid of echo mysql_query(). Then run:
mysql_query($query) or die(mysql_error());
If mysql_query() returns false, which it does upon failure, whatever MySQL error the query generated will now be printed to the screen.
Just a minor note: you should initialize $clean with $clean = array();
If the problem is that the conditional is not firing, then the problem may be elsewhere. Do you have an <input> named "submit" in your form, and is the method of the form post?
Query itself looks okay to me. I think it is difficult to read, so I would do this, but that's just personal style:
$notify = $clean['Notes'] != '' ? '1' : '';
$query = <<<SQL
INSERT INTO test
(Notes, EditoryNotify)
VALUES
($clean[Notes], $notify)
SQL;

Categories