im trying to insert data into a db and I have no clue why its not working.
if(isset($_POST['reply_msg']))
{
$date = date("Y-m-d H:i:s");
$sql = mysql_query("INSERT into pm
(sent_to, sent_by, date, title, content, status)
VALUES('%s','%s','%s','%s','%s','%s')"
, $MSGInfo['sent_by']
, $MSGInfo['sent_to']
, $date
, mysql_real_escape_string($_POST['reply_title'])
, mysql_real_escape_string($_POST['reply_conent'])
, 'Unread');
if (!$sql){
die('Sending failed ');
}
else echo 'Sent!';
}
table screenshot: http://prntscr.com/a2r47v
You should build your query PHP style, not C style. Even so, I would not recommend mysql for this, mysqli is better. Also, take a look at PDO for a higher level of security.
// setup query
$q = "INSERT INTO `pm` ('sent_to', 'sent_by', 'date', 'title', 'content', 'status')) VALUES(
$MSGInfo['sent_to'],$MSGInfo['sent_by'],$date,
mysql_real_escape_string($_POST['reply_title']), mysql_real_escape_string($_POST['reply_conent']),Unread)";
//Run Query
$result = mysql_query($q) or die(mysql_error());
Your query is not quite well built, you need to work a little more at it.
Related
When I submit the form and use this script to insert the data in the db i get the error mentioned above...any ideas?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proCode = $_POST["code"];
$proDescr = $_POST["description"];
$proManu = $_POST["manufacturer"];
$proCPU = $_POST["cost_per_unit"];
$proWPU = $_POST["weight_per_unit"];
$proBarCode = $_POST["bar_code"];
$proIngredients = $_POST["ingredients_list"];
$proAllergens = $_POST["allergens_contains"];
$proMayAllergens = $_POST["allergens_may_contain"];
//Insert users data in database
$sql = "INSERT INTO prodb.simplex_list
code, description, manufacturer,
cost_per_unit, weight_per_unit, bar_code,
ingredients_list, allergens_contains,
allergens_may_contain)
VALUES
( '$proCode', '$proDescr' , '$proManu',
'$proCPU' , '$proWPU' , '$proBarCode',
'$proIngredients' , '$proAllergens',
'$proMayAllergens')";
//Run the insert query
if (!mysql_query($sql)) {
echo mysql_error();
}
?>
UPDATE: I removed id inserts as they are auto-increment and i learned from your answers that a null does not need to be coded and mysql looks after AI. Thanks guys!
Query need to be like:-
$sql = "INSERT INTO prodb.simplex_list
(code, description, manufacturer,
cost_per_unit, weight_per_unit,
bar_code, ingredients_list, allergens_contains,
allergens_may_contain)
VALUES ('$proCode', '$proDescr', '$proManu',
'$proCPU','$proWPU', '$proBarCode',
'$proIngredients', '$proAllergens',
'$proMayAllergens')";
Note:- please stop using mysql_*. Use mysqli_* or PDO. Also this will work only when id field must be auto incremented.
I've been trying to get this INSERT to work correctly, so I worked through the undefined variable and index problems and now I think I am nearly there.
Below is the code:
<?php
session_start();
require "../dbconn.php";
$username = $_SESSION['username'];
$query1 = "SELECT user_table.user_id FROM user_table WHERE user_table.username ='".$username."'";
$query2 = "SELECT department.department_id FROM department, user_table, inventory
WHERE user_table.user_id = department.user_id
AND department.department_id = inventory.department_id";
//Copy the variables that the form placed in the URL
//into these three variables
$item_id = NULL;
$category = $_GET['category'];
$item_name = $_GET['item_name'];
$item_description = $_GET['item_description'];
$item_quantity = $_GET['quantity'];
$item_quality = $_GET['quality'];
$item_status = NULL;
$order_date = $_GET['order_date'];
$invoice_attachment = NULL;
$edit_url = 'Edit';
$ordered_by = $username;
$user_id = mysql_query($query1) or die(mysql_error());
$department_id = mysql_query($query2) or die(mysql_error());
$price = $_GET['price'];
$vat = $_GET['vat%'];
$vat_amount = $_GET['vat_amount'];
$create_date = date("D M d, Y G:i");
$change_date = NULL;
//set up the query using the values that were passed via the URL from the form
$query2 = mysql_query("INSERT INTO inventory (item_id, category, item_name, item_description, item_quantity, item_quality, item_status, order_date,
invoice_attachment, edit_url, ordered_by, user_id, department_id, price, vat, vat_amount, create_date, change_date VALUES(
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$item_quantity."',
'".$item_quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$user_id."',
'".$department_id."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
header( 'Location:../myorders.php');
?>
Error:
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 'VALUES( '', 'adasd', 'dsadsa', 'dsad', 'sadsad', '' at line 2
Could anyone please let me know where I am going wrong? :(
Been staring at this for 3-5 hours already :(
You are not actually trying to insert any data into your table. You only craft and assign the query in string form to a variable. You need to use the function mysql_query to actually run the code.
As pointed out you will also have to specify the columns you are inserting data into in the MySQL query if you don't supply data for every column (in the correct order). Here you can look at the MySQL insert syntax.
I would also urge you to look into using the MySQLi or the MySQL PDO extensions for communicating with your MySQL database since the MySQL extension is deprecated. Look here for additional information and comparisons.
Here, you only assign the values to the $query var:
$query = "INSERT INTO inventory VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')"
or die("Error: ".mysql_error());
You do not actually run the query.
try:
$query = mysql_query("INSERT INTO inventory (column_name1, column_name 2, column_name3 ... the column name for each field you insert) VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
Also, you should use mysqli_* or any other PDO as the mysql_* functions are deprecated
If you are not inserting in all columns you need to specify the columns you are going to insert. Like this:
INSERT INTO Table(Column1, Column6) VALUES (Value1, Value6)
You are missing the column names in your INSERT
I have been using the following query to upload my data into mysql database:
$sql = array();
foreach( $data as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));
Since a bit I have started using PDO and my query looks like this:
$query="INSERT INTO mytable (name, use) VALUES(:sname, :usee)";
$res = $db_conn->prepare($query);
$res->bindValue(':sname',$value);
$res->bindValue(':usee',$_SESSION['usee']);
$res->execute();
Now the above code block is fine, but now when I am going through my CSV upload thing, I again looking backward and using the first code. Want to use the same PDO now for CSV upload also.
Is there a trick to upload multiple values in database using PDO at once?
Yes, you can use some loop in which you will execute, something like this:
$query = $db->prepare(
'INSERT INTO mytable (name, use) VALUES(:sname, :usee)'
);
foreach($mainArrayOfveluus AS $arrayOfValue){
$query->execute(array(
':sname' => $arrayOfValue['sname'],
':usee' =>$arrayOfValue['usee']
));
}
$query->commit();
I'm having trouble getting this to work. I've searched this site and found many other posts regarding this, but none seem to be working.
Here is my simple code:
if (isset($_POST['submit']))
{
$startDate = strtotime($_POST['from']);
$endDate = strtotime($_POST['to']);
for($i = $startDate; $i <= $endDate; $i = strtotime('+1 day', $i))
{
$date = date('Y-m-d',$i);
//echo $date . "<br>";
$sql = ("INSERT INTO `calendar` (`Cal_Date`) VALUES (`$date`)");
}
if(!$result = $db->query($sql))
{
die('There was an error running the query [' . $db->error . ']');
}
}
The form is just as simple and the dates are entered in "YYYY-MM-DD" format. What I'm trying to do is populate my database table with a range of dates. The only thing that happens is one row gets inserted and it is "0000-00-00" and I suspect this is because I've got that column set to Date, Not Null. When I echo the results, everything works perfectly, it's just getting it into the db doesn't seem to work. I've tried many other combinations of the INSERT line including:
$sql = $db->query("INSERT INTO `calendar` (`Cal_Date`) VALUES (`$date`)");
($db is from db_connect.php )
$sql = ("INSERT INTO `calendar` (`Cal_Date`) VALUES (`{$date}`)");
$sql = ("INSERT INTO calendar ('Cal_Date') VALUES ($date)");
$sql = ("INSERT INTO `calendar` (`Cal_Date`) VALUES (`$date`)");
...and I think even a couple of others. I do know that my db_connect.php is connecting to the database as I've got:
$sql = ("SELECT * FROM calendar");
further down the page and it's working fine. I've been going at this for far too long and I'm convinced I'm just missing something obvious. I would appreciate your feedback.
mySQL 5.5.24
PHP 5.3.13
Apache 2.2.22
Try it without the ` for your value, and flicking back to php... as in:
$sql = ("INSERT INTO calendar (`Cal_Date`) VALUES (".$date.")");
If that doesn't help, echo out the SQL and let us know exactly what the built SQL is, that will net you a faster fix
String literals should be quoted with the single-quote ' (or double-quote ", if ANSI_QUOTES is disabled) character, not backticks (which in MySQL are only for quoting SQL identifiers).
First off, there's no need to wrap you string in round brackets!
This should do the trick!
$sql = "INSERT INTO `calendar` (`Cal_Date`) VALUES ('$date')";
An even nicer yet harder to understand solution ( in terms of quotes ) :
$sql = 'INSERT INTO `calendar` (`Cal_Date`) VALUES (\''.$date.'\')';
This one should work as well :
$sql = "INSERT INTO calendar (Cal_Date) VALUES ('$date')";
NOTE : The back-tick ( ` ) is used only for fieldnames and tablenames and needed only if your tablename or fieldname has spaces in it!
Use single or double quotes to delimit strings, dates, chars, varchars within SQL and nothing for booleans, nulls and numeric values!
Hope this helped!
Okay, I have searched for an error in this code for days and haven't succeeded. This is supposed to insert a new user (new row) into a table. For some reason, it does absolutely nothing to the mysql table "users." I can connect and retrieve data from the table perfectly fine. Please help!
include('config.php');
$db = mysql_connect('localhost', $user, $pass);
if(!$db)
{
echo 'Cannot find the database';
exit;
}
$dbname = $user;
mysql_select_db($dbname) or die('Cannot select the database');
(other code that I have not posted because I have tested it without this code and it produces the same result)
$query = "INSERT INTO users VALUES (
NULL,
'$Passw' ,
'$Fname' ,
'$Lname' ,
'$Email' ,
'$Add1' ,
'$Add2' ,
'$City' ,
'$State' ,
'$Zip ,
'$Country' ,
'$Phone' ,
'$Bio')";
$result = mysql_query($query);
1 : Retrieve the possible MySQL error using:
if ($result === false)
echo mysql_error();
2 : It's a good practice to specify the table fields when you use INSERT
INSERT INTO table (field1, field2, field3) VALUES ('value1', 'value2', 'value3');
Because if you don't, and your DB structure changes, you will have to update the VALUES(...) part.
3 : use mysql_real_escape_string() when inserting strings in queries for MySQL, to avoid SQL injection problems.