i keep getting the following error from this simple mysql statement and i cant see why. im sure its something obvious.
require_once("connect.php");
$query = mysql_query("SELECT * FROM accounts ORDER BY id DESC LIMIT 1");
$row = mysql_fetch_assoc($query);
$balanceold = $row['balance'];
$difference = $_POST['predec'].".".$_POST['dec'];
$category = $_POST['category'];
$notes = $_POST['notes'];
if(isset($_POST['in'])){
$balancenew = $balanceold + $difference;
$query = mysql_query("INSERT INTO accounts(currentbalance, balancein, category, notes) VALUES (".$balancenew.", ".$difference.", ".$category.", ".$notes.")");
if($query){
header("Location: budget.php");
}
else{
die(mysql_error());
}
}
gives error:
Unknown column 'payday' in 'field list'
here is my form code:
<form action=process.php method=post>
£
<input type=text name=predec size=7>
.
<input type=text name=dec size=4 value=00>
<br />
<select name=category>
<option value=payday>Payday</option>
</select>
<input type=text name=notes size=20>
<input type=submit name=in value=Deposit>
<input type=submit name=out value=Withdraw>
</form>
database table"accounts" contains the following fields:
id, int primary A_I
balancein, decimal 10,2
balanceout, decimal 10,2
current balance, decimal 10,2
category, varchar 50
notes, varchar 255
date, timestamp
...in that order
try this (enclose each variable inside query with single quota):
mysql_query("INSERT INTO accounts(currentbalance, balancein, category, notes)
VALUES ('$balancenew', '$difference', '$category', '$notes')");
Its better to use mysqli or PDO to prevent from SQL injection attack, you could use mysql_real_escape_string() for now:
$balancenew = mysql_real_escape_string($balancenew);
and for other variables.
Thats because you have syntax error in your INSERT query. String and Date values are to passed into single quotes and not double quotes in sql. the . or the String concatenation character is also not required. So based on the data you provided it might be
$query = mysql_query("INSERT INTO accounts(currentbalance, balancein, category, notes)
VALUES ($balancenew, $difference, '$category', '$notes')");
Basically what sql is telling you that you are referencing a column in your insert that is not defined in the database. Provide your table structure or ensure that the column name is exactly as you defined in the db. HTH.
You have missed single inverted commas enclosing $notes and $category I guess. Enclose them in ' and your problem should be solved.
Related
I've been trying to insert some data into my database for an events page. I have an html form and a seperate script, as seen below and the submit seems to go through for the ename id and imgsrc values but nothing past that. Anything more and I get a 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 'when, descr, positions) VALUES (test, 1 ,www.vzdc.org,2017-1-20 23:59:00' at line 1I've done some reasearch but maybe it's just a weird error on my end? I'm fairly new to mysql and I would love some help! Thanks, code below.
<!-- HTML form -->
<form id="newevent" action="insertevent.php" method="post">
<p>Event Name:</p><input name="ename" type="text" width="100">
<p>ID:</p><input name="id" type="text" size="5">
<p>Banner Link:</p><input name="imgsrc" type="text" size="50">
<p>Description</p><input name="descr" type="text" height="1000px" >
<p>Date / Time (yyyy-mm-dd HH:MM:SS):</p><input name="when" type="text">
<p>Positions (ONE per line)</p><textarea name="positions" form="newevent" rows="10" cols="50"></textarea><br>
<input value="Add Event" type="submit">
</form>
/* PHP script on insertevent.php */
<?php
$link = mysqli_connect("localhost", "root", "xxx", "xxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$ename = mysqli_real_escape_string($link, $_POST['ename']);
$id = mysqli_real_escape_string($link, $_POST['id']);
$imgsrc = mysqli_real_escape_string($link, $_POST['imgsrc']);
$when = mysqli_real_escape_string($link, $_POST['when']);
$descr = mysqli_real_escape_string($link, $_POST['descr']);
$positions = mysqli_real_escape_string($link, $_POST['positions']);
// attempt insert query execution
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Don't use back-ticks for binding variables to your query, use single ticks instead. You can use back-ticks for the table and column name:
INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`)
VALUES ('$ename', '$id', '$imgsrc', '$when', '$descr', '$positions')
WHEN is also a reserved word, so better change its name.
And since you're using mysqli_* API already, check prepared statement
You are using an SQL reserved word as a column name.
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
You really shouldn't, but if you want to get away with this, surround your table/column names with back ticks ```, like this:
$sql = "INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`) VALUES ('$ename', '$id' , '$imgsrc', '$when', '$descr', '$positions')";
I've removed the back ticks you put around your values because, well, they shouldn't be there.
Please learn and use MySQLi prepared statements. They'll help.
<html>
<head>
</head>
<body>
<form action = "insertform.php" method = "post">
field: <input type = "text" name = "fielda">
field2: <input type = "text" name = "fieldb">
thedata: <input type = "text" name = "qdata">
<input type = "submit" name = "submit">
</form>
<?php
if (isset($_POST['submit'])){
$con = mysql_connect("localhost","user","password");
if (!$con){
die("cannot connect" . mysql_error());
}
mysql_select_db("stQutieria",$con);
$sql = "INSERT INTO qtable(fielda, fieldb, qdata) VALUES ("$_POST[fielda]","$_POST[fieldb]","$_POST[qdata]")";
mysql_query($sql,$con);
mysql_close($con);
}
?>
</body>
</html>
Edit: OK! so I changed my code, I played around with double quotes or ' around the $_POST areas. When I used double quotes I got errors saying fielda / fieldb wernt defined, I also got errors saying "syntax error, unexpected '$_POST' (T_VARIABLE)"... the code i am working with derives from the same page ass insertform.php. Here is the video I am watching http://www.youtube.com/watch?v=j4FUCoCxE8w. if anyone could help me on Skype / msn / teamview I would greatly appreciate it.
You're missing quotes around your $_POST keys: $_POST[fielda] should be $_POST['fielda'] etc. (actually not true)
You need a space after your table name and opening parenthesis qtable(fielda should be qtable (fielda
You're missing a quote after '$_POST[fielda] (should be '$_POST[fielda]') and after '$_POST[fieldb] (should be '$_POST[fieldb]')
You have no error handling. If you call mysql_error() after your query you would know exactly what your error is.
You are wide open to SQL injections
You are using an obsolete API
That means your query is failing. Likely because you have no space between the table name and the column names:
INSERT INTO qtable (fielda, fieldb, qdata)
replace Your SQL with:
$sql = "INSERT INTO qtable (fielda, fieldb, qdata) VALUES ('".$_POST['fielda']."','".$_POST['fieldb']."','".$_POST['qdata']."')";
but this is really unsafe...
Much more safer is to use something like this:
$values = array($_POST['fielda'], $_POST['fieldb'], $_POST['qdata']);
$st = $db->prepare('INSERT INTO qtable (fielda, fieldb, qdata) VALUES (?,?,?)');
$st->execute($values);
You are making mistake in coding the correct sql statement will be like this one
$sql ="INSERT INTO qtable(fielda, fieldb, qdata) VALUES (".$_POST[fielda].",".$_POST[fieldb].",".$_POST[qdata].")";
Note this above sql statement is for those fields which are integer in database if fields are varchar then following will be code
$sql ="INSERT INTO qtable(fielda, fieldb, qdata) VALUES ('".$_POST[fielda]."','".$_POST[fieldb]."','".$_POST[qdata]."')";
Thank You
I'm getting a mysql error saying "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..."
Here's the basics of my code:
First I'm populating the select menu options with rows from the categories table. This is working fine:
<select id="dropdown-select" name="Name">
<option value="" id="dropdown-option">Please select a category.</option>
<?php
$query_categories = "SELECT * FROM categories";
$result_categories = mysql_query($query_categories) or die(mysql_error());
while($categories_row = mysql_fetch_array($result_categories)) {
echo '<option id="dropdown-option" value="' . $categories_row['cat_name'] . '">' . $categories_row['cat_name'] . '</option>';
}
?>
</select>
Later, when I go submit the form to the transactions table (the above table I pulled data from was the categories table, could this be a problem?) is when I get the error. I think its related to the above code bc if I remove this element from my form submission, it writes the rest of the values to the database without any errors.
if(!isset($_POST['Name'])) {
die('You must select an income or expense from the drop down menu.');
} else {
$Name = $_POST['Name'];
}
//create query
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month', '$Name', $Budgeted', '$Actual')";
$result = mysql_query($query) or die("Error in query: $query. " . mysql_error());
Thanks for any help you can provide.
You are missing a single quote in your insert statement before $Budgeted
INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month', '$Name', '$Budgeted', '$Actual')"
If you have some fields which are defined in Database as VARCHAR, CHAR.
Also, if you are inserting a string value in Database from a PHP script, you need to add an enclosing single quote (') around it.
In your case, you are inserting a string without semicolons, so, it showing error in MySQL.
Your statement should be corrected by adding a single quote around $budget as:
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month',
'$Name', '$Budgeted', '$Actual')";
------^
The error "You have an error in your SQL syntax" is exactly correct!
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual)
VALUES ('$Month', '$Name', $Budgeted', '$Actual')";
Look here, you missed something ----^
There is a ' missing from your statement causing the syntax error. Put the single quote in and you should be good to go!
I'm trying to update a table from a form.
I have 3 pages. The first one queries all of the rows from my table with an "edit" link.
When edit is clicked (page 2) the code pulls the $id and puts it in the url. The $id is pulled from the url and is used in a query to fill a form.
My problem is passing the updated form info to my table. Basically the update isn't happening.
Second page
<?php
include '../db/config.php';
include '../db/opendb.php';
$id = $_GET["id"];
$order = "SELECT * FROM tableName where id='$id'";
$result = mysql_query($order);
$row = mysql_fetch_array($result);
?>
<form method="post" action="edit_data.php">
<input type="hidden" name="id" value="<?php echo "$row[id]"?>">
<tr>
<td>Title</td>
<td>
<input type="text" name="title" size="20" value="<?php echo"$row[title]"?>">
</td>
</tr>
<tr>
<td>Post</td>
<td>
<input type="text" name="post" size="40" value="<?php echo
"$row[post]"?>">
</td></tr>
<tr>
<td align="right">
<input type="submit" name="submit value" value="Edit">
</td>
</tr>
</form>
third page
include '../db/config.php';
include '../db/opendb.php';
$query = "UPDATE tableName SET '$_POST[title]', '$post[post]' WHERE id='$id'";
mysql_query($query);
It should be
UPDATE tableName SET `title` = {$_POST['title']}, `post` = {$_POST['post']}...
Ask yourself, what are you setting?
Your SQL statement for the database update is wrong. It should include a listing of not only the new values but also the corresponding field names. This means it should look more like this:
$query = "UPDATE tableName SET `title` = {$_POST['title']}, `post` = {$_POST['post']} WHERE id = '$id'";
Notice that you also should embrace fields of $_POST inside of strings with curly brackets ({}) or put them outside of the quotes. (like " = " .$_POST['title']. ", "). This is absolutely necessary if you use the standard way to access those with he quotes (e.g. not $_POST[title] but $_POST['title'] or $_POST["title"]).
Additionally you should add the following to your code:
Some error handling, currently you don't even know if something went wrong. The simplest way is to check the return value of the mysql_query() function for null and if it is null, get the mysql error message with mysql_error().
Escaping for passed values. Currently you directly pass the posted data into a mysql query which is very insecure. (See for example SQL-Injection on wikipedia) You should use mysql_real_escape_string() on all form data before inserting them into queries. This escapes all parts that could be malicious.
if (isset($_POST[title])){
$title = mysql_real_escape_string(trim($_POST['title']));
}else{
$title = NULL;
}
if (isset($_POST[post])){
$post = mysql_real_escape_string(trim($_POST['post']));
}else{
$post = NULL;
}
$query = "UPDATE tableName SET title='$title', post='$post' WHERE id='$id'";
mysql_query($query);
I would also recommend mysqli functions instead of mysql and I probably wouldn't call a variable and table column 'post' to avoid confusion.
That is because you are not setting the values. In the statement:
$query = "UPDATE tableName SET '$_POST[title]', '$post[post]' WHERE id='$id'";
you should pass column names to be updated.
If you are not using PDO statements yet to prevent SQL injection attacks then you should use more protection then just mysql_real_escape_string(). On top of escaping the data you should be validating that the submitted data is in fact what you are expecting.
Ie. In your code here:
$id = $_GET["id"];
$order = "SELECT * FROM tableName where id='$id'";
$result = mysql_query($order);
$row = mysql_fetch_array($result);
If you added:
if(is_numeric($_GET['id'])){
$id = mysql_real_escape_string(trim($_GET["id"]));
$order = "SELECT id, title, post FROM tableName where id='$id'";
$result = mysql_query($order);
$row = mysql_fetch_array($result);
}
This would at least validate what you are executing is in fact an ID number (That is, if ID is actually a number ;) . You can apply this logic to all your inputs if you are not yet using PDO statements. If you are expecting letters then validate for letters, numbers validate for numbers, escape special characters. Again, this is bare minimum. I would really suggest reading up on the hundreds of SQL injection techniques and start reading up on PDO's.
Also, in regards to using the SELECT * statement. I would try and avoid it. It adds a layer of vulnerability to your statements, if you change the order of the fields in your table and you are using $row[0] (Numbered requests) it can muck things up and lastly if your table contains additional fields with data that is unrelated to the ones you need then you are using on this page then you are loading information you don't need to.
$order = "SELECT id, title, post FROM tableName where id='$id'";
Would solve that nicely. :) Good luck!
I am getting an error when trying to insert some values into a MySQL Database - My page currently reads the value 'EventID' which is passed through the URL and allows me to Add Results based on that EventID. I currently have a Drop down box which is populated by the Members within the members table.
I get this horrid error:
Cannot add or update a child row: a foreign key constraint fails (clubresults.results, CONSTRAINT ResultEvent FOREIGN KEY (EventID) REFERENCES events (EventID) ON DELETE CASCADE)
I am not able to change the table structure so any help would be great appreciated.
Note - I'm currently having it echo the SQL to find the error as to why it won't insert.
<?php
error_reporting (E_ALL ^ E_NOTICE);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("clubresults", $con);
// Get id from URL
$id = mysql_real_escape_string($_GET['EventID']);
// If id is number
if ($id > 0)
{
// Get record from database
$sql = "
SELECT EventID
FROM results
WHERE EventID = " . $id;
$result = mysql_query($sql);
}
if (isset($_POST['submit'])) {
$sql="INSERT INTO results (MemberID, Score, Place)
VALUES
('".$_POST['student']."', '".$_POST['Score']."', '".$_POST['Place']."')";
$add_event = mysql_query($sql) or die(mysql_error());;
echo $add_event;
}
HTML Form -
$_SERVER['PHP_SELF']?>" method="post">
<table border="0"><p>
<tr><td colspan=2></td></tr>
<tr><td>Member Name: </td><td>
<?php
$query="SELECT * FROM members";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
$result = mysql_query ($query);
echo "<select name=student value=''>Student Name</option>";
// printing the list box select command
while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value='$nt[MemberID]'>$nt[Firstname] $nt[Surname]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>
<tr><td>Score:</td><td>
<input type="text" name="Score" maxlength="10">
<tr><td>Place:</td><td>
<input type="text" name="Place" maxlength="10">
</td></tr>
<tr><th colspan=2><input type="submit" name="submit"
value="Add Result"> </th></tr> </table>
</form>
You have to insert the EventID into your results record:
$sql="INSERT INTO results (MemberID, Score, Place, EventID) VALUES (?, ?, ?, ?)";
Note I have used ? placeholders in place of your $_POST variables (which left you vulnerable to SQL injection).
You should use instead prepared statements into which you pass your variables as parameters that do not get evaluated for SQL, but they are not available in the ancient MySQL extension that you're using (which the community has begun deprecating anyway, so you really should stop writing new code with it); use instead either the improved MySQLi extension or the PDO abstraction layer.