Why is my SQL "INSERT INTO" query not working? - php

I'm making a storage log for work, and I've been fighting with this code for the last two hours with no success. For some reason, no matter how many times I check and recheck the code for my INSERT INTO query, it will not work.
Keep in mind that I copied this code, almost verbatim (changed the form names and fields, obviously) from another page that has basically the same functionality and works 100%. Code below:
This is the page containing the form where the transaction is being submitted:
<?php
$script = '<script>
$(document).ready(function(){
$(".datepicker").datepicker();
}); </script>' ;
$title = "View/Edit Storage - " ;
include('inc/header.php');
?>
<table>
<tr>
<form action="transadded.php" name='addnewtransaction' method="POST">
<td><input type="text" name="moveID" size="20" value="<?php echo $results[moveid]; ?>" readonly> </td>
<td><select id="inoutselect" name="inorout">
<option value="Select">Select</option>
<option value="Storage In">Storage In</option>
<option value="Storage Out">Storage Out</option>
</select> </td>
<td><input type="text" name="numberofunits" size="20"></td>
<td><input type="text" name="dateoftransaction" size="20" class="datepicker"></td>
<td><input type="text" name="rrdt" size="20"> </td>
<td><input type="submit" value="Add" id="logsubmit"></td>
</form>
</table>
<br /><br />
<?php };?>
Here's the query itself, aka "transadded.php":
<?php
$title = "Project Added - ";
include('inc/header.php');
$query = "INSERT INTO newtransaction (moveid, inout, units, transdate, refno) VALUES('$_POST[moveID]','$_POST[inorout]','$_POST[numberofunits]','$_POST[dateoftransaction]','$_POST[rrdt]')";
if(!mysqli_query($con,$query))
{
die ('Error: ' . mysqli_error($con));
}
echo '<div class="transstatus">' . '1 record added' . '</div>';
mysqli_close($con);
?>
The header, obviously, contains the function for connecting to the database, and as I said, another query works just fine with it, so I know that that isn't the problem. Upon clicking the submit button, the error I get on the page is as follows:
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 'inout, units, transdate, refno) VALUES ('1234567','Storage In','81','09/11/2013'' at line 1
Here, "1234567", "Storage In", etc are the values I enter into the form.
I hope you can help me out. I'm so stuck!
Also, I know that I'm not protected against injection right now. I plan to work on that later, but I'm trying to get the functionality straightened out first.

INOUT is a MySQL reserved word.
See here: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Change the name or put it in quotes.

Use the following:
$query = "INSERT INTO newtransaction (
`moveid`, `inout`, `units`, `transdate`, `refno`
)
VALUES(
'{$_POST[moveID]}', '{$_POST[inorout]}',
'{$_POST[numberofunits]}', '{$_POST[dateoftransaction]}',
'{$_POST[rrdt]}'
)
";

$query = "INSERT INTO newtransaction (moveid, inout, units, transdate, refno)
VALUES
( '".$_POST['moveID']."','".$_POST['inorout']."','".$_POST['numberofunits']."',
'".$_POST['dateoftransaction']."','".$_POST['rrdt']."')";
you post your like ='$_POST[dateoftransaction]'
right procedure is if you using wamp= '".$_POST['dateoftransaction']."'
i hope you got your mistake
Ferrakkem

Related

cannot add to database mysql

I am having trouble with my form adding to my database.
I have made the form and the script but am having trouble implementing them. Any ideas?
Table:
Here is the HTML form:
<form method="post" id="form2" action="home.php?id=<?php echo "$user_id";?>"> </br>
<h2>What would you like to ask? Rant away!</h2>
<input type="text" name="title" placeholder="Write a title" size="92px"/>
<textarea cols= "70px" rows="6px" name="content";>Description...</textarea><br/>
<select name="topic">
<option> Select Topic</option>
<?php getTopics() ;?>
</select>
<input type="submit" name ="submitbtn" value="Post to Timeline"/>
</form>
<?php
insert_post();?>
Here is the function - the file the function is in, is included in the HTML file using the include command at the top of the file.
function insert_post(){
if(isset($_POST['submitbtn'])){
global $con;
$title=$_POST['title'];
$content=$_POST['content'];
$topic=$_POST['topic'];
$insert="INSERT INTO `posts` ( `user_id`, `topic_id`, `post_title`, `post_content`, `post_date`)
VALUES ('$user_id','$topic','$title','$content',NOW()) ";
$run=mysqli_query($con, $insert);
if($run){
echo"<h3>Discussion posted</h3>";
}
}
}
EDIT:
For reference, the error I get when clicking the submit is a 404 which says "object not found".
EDIT 2:
Image of table shows the row is called pos_title whereas my own code says post_title. When code was edited to say pos_title, the same error still arose.
EDIT 3:
New errors after implementing some suggested changes:
Remove if(isset($_POST['submitbtn'])){ from the functions and add this above the form:
if(isset($_POST['submitbtn'])){
insert_post();
}
Change action to action="home.php".
Add this code to form:
<input value="<?php echo $user_id?>" type="hidden" name="user_id">
Add this code to insert_post function:
$user_id = (int)$_POST['user_id'];
Replace post_title to pos_title or alter your table.
You don't need the quotes in '$user_id', '$topic', but MySQL will still accept it.
$insert="INSERT INTO `posts` ( `user_id`, `topic_id`, `post_title`, `post_content`, `post_date`)
VALUES ('" . $user_id . "','" . $topic . "','" . $title . "','" . $content . "',NOW()) ";
Try this code. You should concatenate using the . instead of inserting variables in the string:
$run=mysqli_query($con, $insert);
if($run) {
echo"<h3>Discussion posted</h3>";
} else {
echo mysqli_error($con);
}
NOTE:
also for debugging purposes you should check mysqli_error($con); if there's an error.
<form method="post" id="form2" action="home.php?id=<?php echo $user_id;?>"> </br>
When you echo a variable there is no need for double quotes. It is a variable not a string.
<textarea cols= "70px" rows="6px" name="content">Description...</textarea><br/>
And you have a semicolon after name="content" that should not be there as well.
I want to thank you all for your time and effort and help. It turned out there had been a syntax error about 400 lines higher than this form at the previous form, where I'd typo'd when closing it. So the question I had asked was unsolvable for you as it turns out the code shared was more or less fine. So very big apologies for my mistake guys and thanks so much for all your help. This has certainly taught me to clean up my html files and not let them get so big!

updating mysql through form data retains old values

I am battling with the below code. The below is intended to:
1) Read data course data from database
2) Display data in a form ready for editing
3) Once edited, on submit, pass edited values to database
The issue I am getting is that I am able to execute 1 and 2 with no issues, but when I pass the edit data to database in step 3, the old values which where presented in step one are instead passed. How to I get the edited values to be passed and not the old values?
Thank you in advance
$readQuery="SELECT * FROM course WHERE course_id={$id}";
$readResult=mysqli_query($connection, $readQuery);
validateQuery($readResult);
while($row=mysqli_fetch_assoc($readResult))
{
$courseId=$row["course_id"];
$courseName=$row["course_name"];
$courseDescr=$row["course_descr"];
$courseCost=$row["course_cost"];
$courseDuration=$row["course_duration"];
}
?>
<form action="course_man.php?page=<?php echo $page?>" &id=<?php echo $id?>" method="post">
<table>
<tr>
<td align="right">
<!--Course ID <input type="text" name="course_id" value="<?php //echo $courseId;?>"/><br/>-->
Course Name <input type="text" name="course_name" value="<?php echo $courseName;?>"/><br/>
Course Description <textarea name ="course_descr" rows="6" cols ="30" ><?php echo $courseDescr;?></textarea><br/>
Course Cost <input type="text" name="course_cost" value="<?php echo $courseCost;?>"/><br/>
Course Duration <input type="text" name="course_duration" value="<?php echo $courseDuration;?>"/><br/>
<input type="submit" name="update" value="Update"/>
</td>
</tr>
</table>
</form>
<?php
}
if(isset ($_POST['update']))
{
$updateQuery="UPDATE course SET ";
$updateQuery.="course_name='{$courseName}', ";
$updateQuery.="course_descr='{$courseDescr}', ";
$updateQuery.="course_cost={$courseCost}, ";
$updateQuery.="course_duration={$courseDuration}, ";
$updateQuery.="WHERE course_id={$id}";
$check = mysqli_query($connection, $updateQuery);
mysqli_error($connection);
}
Go through your code line-by-line. How is the script supposed to get the new values from the form? A sql query is executed in all cases and the variables such as $courseName are set with the old values anyway. Now, when we get to the updating part, variables are still set with old values.
if(isset ($_POST['update']))
{
$updateQuery="UPDATE course SET ";
$updateQuery.="course_name='". $_POST['course_name'] ."', ";
$updateQuery.="course_descr='". $_POST['course_descr'] ."', ";
$updateQuery.="course_cost=". $_POST['course_cost'] .", ";
$updateQuery.="course_duration=". $_POST['course_duration'] .", ";
$updateQuery.="WHERE course_id=". $_POST['course_id'];
$check = mysqli_query($connection, $updateQuery);
mysqli_error($connection);
}
Move this code up before SELECT... query. And do not forget to sanitize user data before putting it into the query! Use mysqli_real_escape_string() http://php.net/manual/en/mysqli.real-escape-string.php or something else.
When you submit form to course_man.php it again fetch data from db and your below variables will be overwritten with db values.
$courseId=$row["course_id"];
$courseName=$row["course_name"];
$courseDescr=$row["course_descr"];
$courseCost=$row["course_cost"];
$courseDuration=$row["course_duration"];
Try this ....
$updateQuery="UPDATE course SET course_name = '$courseName',
course_descr = '$courseDescr',
course_cost = '$courseCost',
course_duration = '$courseDuration'
WHERE course_id = $id
";

Grabbing IP on submit, SQL syntax error

After browsing google for a few hours, I managed to splice together some code up, and it looks like it's working for the most part. Unfortunately, I'm getting an SQL error when I submit my form.
What I'm trying to do: When someone fills out the form on my website, a specific function is applied based on which radio button is pressed in the form. I want to store the data in a database, but I also want to store the IP address of the individual submitting.
All I request of this wonderful community is an explanation of why this isn't functioning as I thought it should, and a quick lesson on how to prevent this from happening again.
Here is the code for my form:
<html>
<head>
<link rel="stylesheet" type="text/css" href="/style.css">
<title>
Learning Made Easy
</title>
</head>
<body>
<?php include_once 'googleanalytics.php'; ?>
<a href="http://terrythetutor.com">
<div class="banner"> </div>
</a>
<?php include 'menu.php'; ?>
<div class="content">
</br>
</br>
</br>
<form action="../scripts/switch.php" method="post">
Title:
</br><input type="text" name="Title">
</br>
</br>
</br>
Summary of the video (including questions used in the video):
</br><textarea name="Summary" COLS=60 ROWS=10></textarea>
</br>
</br>
</br>
URL of the video (Yes, this means you need to upload it to an external website.):
</br><input type="text" name="URL">
</br>
</br>
Which course does your video pertain to?</br>
<input type="radio" name="course" value="intermediate"> Intermediate and below</br>
<input type="radio" name="course" value="college"> College Algebra</br>
<input type="radio" name="course" value="precalculus"> PreCalculus</br>
<input type="radio" name="course" value="trigonometry"> Trigonometry</br>
<input type="radio" name="course" value="calculus I"> Calculus I</br>
<input type="radio" name="course" value="calculus II"> Calculus II</br>
<input type="radio" name="course" value="calculus III"> Calculus III</br>
<input type="radio" name="course" value="differential equations"> Differential Equations</br>
</br>
The function triggered is used to pick the correct function based on the radio button selected. For the sake of space I won't include it, and will skip right to the code that it redirects to. This is where (I suspect) my error is, and I'm unfortunately not well versed enough to solve this error alone.
Code of the function AFTER switch.php (this is where I define the IP variable):
<?php
// Create connection
$con=mysqli_connect("********","*****","*****","****");
$IP = $_Server['REMOTE_ADDR'];
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Intermediate Algebra ('Title', 'URL', 'IP', 'Summary')
VALUES
('$_POST[Title]','$_POST[URL]','[$IP]','$_POST[Summary]'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Your video has been successfully submitted. Thank you for your contribution to TerryTheTutor.com";
header('Location:http://terrythetutor.com');
?>
</br>
<input type="submit" value="Submit, foo!">
</form>
</br>
</br>
</br>
<p>
Please understand that you will not be able to change the title, summary, or URL of your video after submission.
</p>
</div>
<div class="footer">
<?php include 'footer.php'; ?>
</div>
</body>
</html>
I believe that the error has originated with the $IP variable. I've tried to add quotes, scanned the code countless times and still am unsure of what the error is.
Here is what the error I'm getting when I submit looks like:
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 'Algebra ('Title', 'URL', 'IP', 'Summary') VALUES ('Title Test','Url test','[]',' at line 1
As a courtesy, if someone could show me how to properly "sanitize" this data input, that would be wonderful.
Thank you, guys!
table names and column names are identifiers. they are not string literals so they should not be wrap with single quote. So you need to remove it eg
INSERT INTO `Intermediate Algebra` (Title, URL, IP, Summary) VALUES(....)
If it happens that the names contains spaces or a reserved keyword, it should be wrap with backticks. eg
INSERT INTO `Intermediate Algebra` (`Title`, `URL`, `IP`, `Summary`) VALUES(...)
Additional Info
MySQL Reserved Keywords List
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
You can try this, this will help you to run your script successfully without any error.
$sql="INSERT INTO `Intermediate Algebra` (`Title`, `URL`, `IP`, `Summary`)
VALUES ('".$_POST[Title]."','".$_POST[URL]."','".$IP."','".$_POST[Summary]."')";
You have more than one error here:
PHP variable names are case sensitive. This means you have an error in this line of code:
$IP = $_Server['REMOTE_ADDR'];
Thus, $IP is always empty.
Instead, this should be:
$IP = $_SERVER['REMOTE_ADDR'];
In your SQL statement, table names with spaces need to be backquoted. It's also a very good idea to do the same with your field names, to avoid conflicts with MySQL keywords:
$sql="INSERT INTO `Intermediate Algebra` (`Title`, `URL`, `IP`, `Summary`) VALUES(...)";
Finally, your SQL statement is vulnerable to SQL injection and needs to be completely rewritten and replaced with a prepared statement.
You need to close bracket ),
('$_POST[Title]','$_POST[URL]','$IP','$_POST[Summary]')";
SQL:
$Title = mysqli_real_escape_string($con, $_POST['Title']);
$URL = mysqli_real_escape_string($con, $_POST['URL']);
$IP = $_SERVER['REMOTE_ADDR'];
$IP = mysqli_real_escape_string($con, $IP);
$Summary = mysqli_real_escape_string($con, $_POST['Summary']);
$sql="INSERT INTO Intermediate Algebra ('Title', 'URL', 'IP', 'Summary')
VALUES
('$Title','$URL','$IP','$Summary')";

Adding post values to database using mysqli

I seem to have an issue inserting the post values into my database, and i don't see the error in the coding. I've been looking at it for a while now and to me everything looks right, however when i use the form and submit the data the page reload but no data get inserted into the database.
It would be much appreciated if someone could help me identify the error in the coding.
If you have any questions feel free to ask!
Kind regards Jim
FORM
<?php
//Show the form if the user is a Admin
if(isset($_SESSION['username'])){
$username == $_SESSION['username'];
$results = $mysqli->query("SELECT authority FROM users WHERE username='$username' LIMIT 1");
while($row = $results->fetch_object()){
$aut = $row->authority;
}
}
if($aut == 1){
?>
<form action="index.php" method="post">
<table>
<tr>
<td> Title: </td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td valign="top"> News: </td>
<td><textarea name="information"></textarea></td>
</tr>
<tr>
<td> <input type="hidden" value="news"> </td>
<td><input type="submit"></td>
</tr>
</table> <hr>
</form>
MYSQLI
<?php
}
//Insert into the database
if(isset($_POST['news'])){
$title = $_POST['title'];
$information = $_POST['information'];
$mysqli->query("INSERT INTO `news` (`title`, `information`) VALUES ( '".$title."', '".$information."')");
}
<input type="hidden" value="news"> should be <input type="hidden" name="news">
That's why isset($_POST['news']) will never be true.
Beside that silly typo problem your code suffers from two real disasters.
You have no error reporting, which renders you helpless against such silly mistakes
You are adding your data directly into query, while ought to use placeholders for that.
I am not sure what was intended with the backticks and periods in your original query. In my limited experience my queries take the form of:
$mysqli->query("INSERT INTO news(title, information) VALUES ('$title', '$information')");
I would say that priority #1 is getting some debugging information in the form of return values for your php functions or access to php error logs.

php form mysql error to database

I have a form that does not seem to want to write its data to my database. I am somewhat new to php mysql. When I test the script the page reloads with only a "0" displayed. I am not sure what am I missing? Any help is appreciated.
form
<form action="new.php" method="POST">
<table>
<tr>
<td>Season Number: </td>
<td><input type="text" name="season_sum" size="50" value="<? echo "$season_num";?>"></td>
</tr>
<tr>
<td>Episode Number: </td>
<td><input type="text" name="eps_num" size="50" value="<? echo "$eps_num";?>"></td>
</tr>
<tr>
<td>Temp Episode Number: </td>
<td><input type="text" name="temp_eps_num" size="50"></td>
</tr>
<tr>
<td>Title: </td>
<td><input type="text" name="title" size="50"></td>
</tr>
<tr>
<td>Description: </td>
<td><textarea type="text" name="descrip" cols="50" rows="7"></textarea></td>
</tr>
<tr>
<td colspan="2"><input type="hidden" name="id">
<input type="Submit" value="New Item"></td>
</tr>
</table>
</form>
new.php
<?php
require "db.php";
//Test for user input
if (!empty($_POST[season_sum])&&
!empty($_POST[eps_num])&&
!empty($_POST[temp_eps_num])&&
!empty($_POST[title])&&
!empty($_POST[descrip]))
if ( ! empty($_POST['ID']))
$id = (int)$_POST['ID'];
else $id = 'NULL';
//Insert new entry
$query = "INSERT INTO `season` (`ID`, `season_num`, `temp_eps_num`, `esp_num`, `title`, `descrip`) VALUES ({$id}, '{$season_sum}', '{$eps_num}', '{$temp_eps_num}', '{$title}', '{$descrip}')";
// Send user back to the list once the update is successfully finished
header("Location: form.html");
?>
Disable the following line in new.php in the event the PHP code is throwing an error:
//header("Location: form.html")
Then you will need to execute the $query using mysql_query.
$query = "INSERT INTO ... ";
mysql_query($query);
you are never actually sending the query, just defining the query string. To send it you netted to use mysql_query ($query).
See documentation for more details. http://php.net/manual/en/function.mysql-query.php
Not sure about the "0" but in general your code looks like you chopped things out for readability. If not...
if (!empty($_POST[season_sum]) && !empty($_POST[eps_num]) && !empty($_POST[temp_eps_num]) && !empty($_POST[title]) && !empty($_POST[descrip]))
{
if ( !empty($_POST['ID']))
$id = (int)$_POST['ID'];
else
$id = 'NULL';
// mysql_real_escape_string() example
$descrip = mysql_real_escape_string($_POST['descrip']);
//Insert new entry
$query = mysql_query("INSERT INTO `season` (`ID`, `season_num`, `temp_eps_num`, `esp_num`, `title`, `descrip`) VALUES ({$id}, '{$season_sum}', '{$eps_num}', '{$temp_eps_num}', '{$title}', '$descrip')") or die(mysql_error());
// Send user back to the list once the update is successfully finished
header("Location: http://www.yoursite.com/form.html");
exit;
}
I didn't put in the escaping since it is easier just to suggest you wrap your db insert strings with mysql_real_escape_string(). Aside that you never actually run a query, and you do not wrap your if statement with curly braces. I don't even know what the page would think to do in this condition.
Try applying these changes and let us know if the error persists.
note - I added exit after your header location. Also, I put a full url path in as somewhere or another I heard this was better practice. I have no backing for that claim though. Just a thing I heard somewhere.
mysql_real_escape_string() explanation:
to use it you must have a connection open. This is usually handled in your db class so if you discover it doing nothing, look into mysql_connect();
To use, just call like so:
$sql = mysql_query("SELECT * FROM `table` WHERE `id` = '".mysql_real_escape_string($string_to_escape)."'");
It will not add the single quote wrapper. All it does is help sanitize the string to prevent common sql injection attacks.

Categories