I am getting this error here is my code
if(isset($_POST['submit']))
{
$projTit=mysql_escape_string($_POST['projecttitle']);
$projCat=mysql_escape_string($_POST['projectcategory']);
$budget=intval(mysql_escape_string($_POST['budget']));
$description=mysql_escape_string($_POST['editor1']);
$query=sprintf("insert into projects value('%s','%s','%s',%d)",
$projTit,$description,$projCat,$budget);
if (!mysql_query($query)){
die('Error: ' . mysql_error());
}
echo '<p class="record">Your Record has been Added<p>';
}
?>
I have tried to write %d in '' but still not working.
Your table has five columns. However, you are not providing a value for the Project_Id column. This gives you the error you mentioned.
I understand that you're not providing a value since it's likely a PRIMARY KEY that autoincrements. To tell MySQL that you are intentionally not passing a value for that column, you should add NULL as the first value.
value(NULL, '%s','%s','%s',%d)
However, you really should specifically name which columns you are inserting into in case you add a new column at a future date.
INSERT INTO projects (col1, col2, col3, col4) value ('%s','%s','%s',%d)
You should really specify the column names or your app will break if you add a column later, even if it has a useable default value:
INSERT INTO projects
(Project_Title, Project_Description, Project_Category, Project_Budget)
VALUES
(...)
Especially since you have an auto_increment ID column it makes sense; otherwise you'd always have to specify it as NULL in your query.
The easiest (but also ugliest) fix would thus be:
$query=sprintf("insert into projects value (null, '%s','%s','%s',%d)",
$projTit,$description,$projCat,$budget);
The good fix would be this:
$query = sprintf("
INSERT INTO projects
(Project_Title, Project_Description, Project_Category, Project_Budget)
VALUES
('%s', '%s', '%s', %d)
", $projTit,$description,$projCat,$budget);
By the way, consider using PDO - then you can use something similar to a format string but don't have to deal with escaping.
try naming the columns you want to fill like
insert into projects (col1, col2, col3) values (...)
Related
I'm trying to add a few Primary Keys from different tables as Foreign Keys to one Main table in a Query in php.
So far I got:
$result=$mysqli->query("INSERT INTO m_main (M_Id, M_T_Id, M_U_Id, M_P_Id, M_S_Id, M_Sp_Id, M_Ra_Id, M_F_Id, M_Hp, M_Rss, M_Kommentar)"
. "VALUES (DEFAULT, 123, 123, '".$_SESSION['sId']."' , 123, '".$_SESSION['Sp_Id']."', '".$_POST['fragestellung']."', 123,"
. "'".$_POST['hp']."', $rss, '".$_POST['kommentar']."')");
Every "123" I want to replace with an existing Primary key from other tables from my database.
How is this possible ?
You can use the INSERT ... SELECT syntax.
Something like this where anotherTable is the other table you want to insert from.
$result=$mysqli->query("INSERT INTO m_main (M_Id, M_T_Id, M_U_Id, M_P_Id, M_S_Id, M_Sp_Id, M_Ra_Id, M_F_Id, M_Hp, M_Rss, M_Kommentar) "
. "SELECT (DEFAULT, anotherTable.id, anotherTable.id, '".$_SESSION['sId']."' , anotherTable.id, '".$_SESSION['Sp_Id']."', '".$_POST['fragestellung']."', anotherTable.id,"
. "'".$_POST['hp']."', $rss, '".$_POST['kommentar']."') FROM anotherTable");
If needed you can also limit the number of inserted rows into m_main with a WHERE clause in the SELECT statement.
A long time ago I asked this question. Finally I found some time to answer it in case anybody has the same problem. Don't know why I wanted to make it so complicated. Subquerys where the answer:
$result=$mysqli->query("INSERT INTO m_main (M_Id, M_T_Id, M_U_Id, M_P_Id, M_S_Id, M_Sp_Id, M_Ra_Id, M_F_Id, M_Hp, M_Rss, M_Kommentar)"
. "VALUES (DEFAULT, (SELECT MAX id FROM title), (((AND SO ON...)))
I have an issue where I can only insert data into my table once. If i delete the row and insert a new one, it works but if I already have a row and try to insert another one, it doesn't work. No errors in the console or network.
I'm inserting with this:
<?php
error_reporting(E_ALL);
include 'DB.php';
$con = mysql_connect($host,$user,$pass)
or die("Error: ".mysql_error());
$dbs = mysql_select_db($databaseName, $con);
$name = mysql_real_escape_string($_POST['name']);
$date = date('Y-m-d');
$amount = $_POST['amount'];
$timPaid = $_POST['timPaid'];
$rennyPaid = $_POST['rennyPaid'];
$sql = "INSERT INTO $tableName (`name`, `date`, `amount`, `timpaid`, `rennypaid`)
VALUES ('$name', '$date', '$amount', '$timPaid', '$rennyPaid')";
$result = mysql_query($sql, $con)
or die("Error: ".mysql_error());
mysql_close($con);
?>
I'm thinking it might have to do with how my table is set up, primary key and such. I have an id column which is the primary and I think it's auto-increment, can't tell.
Since you are not sure about whether the id field is auto-increment or not, you should alter your table like this,
ALTER TABLE `yourtable`
MODIFY COLUMN `id` int(11) NULL AUTO_INCREMENT FIRST;
the result FROM SHOW CREATE TABLE tableName would help.
I would guess you have a unique index on on of your fields and you are trying to insert a second record with the same value.
Also CHECK TABLE tablename could help identify the problem.
I had this... I had set my first column as 'unique' and my 'Insert' didn't involve that column.
As a result the 'Insert' added a value of zero into the 'Unique' column (I'd set that column to 'integer').
When I did another insert 'I THINK' that the 'Insert' wanted to add another zero in the 'Unique' column that I wasn't 'Inserting' into, so it tried to 'Insert' another zero, BUT because that column was 'unique' it wouldn't allow another zero and refused the 'Insert'.
I proved this by changing the first 'Inserts' entry into the 'Unique' column manually to another 'Integer' then the 'Insert; statement worked one more time.... repeat process above as described and my table allowed another 'Insert'.
Hope this makes sense and helps?.
I had a similar problem, however mine was where I was using the INT data type in my create table script for storing a 13-digit long number, and it only wanted to accept something 10-digits in size. Changing this to a VARCHAR(13) fixed the problem for me.
In my Document table I have:
id (auto int index),
user_id (P.key and links to other table),
Doc_Name,
abstract
When I use the code below, it just inserts another row so I have two user_id's the same when it should have updated. Obviously the id just carries on in number as it is auto int and I'm not sure if this has something do with why it won't work.
$the_query = sprintf("INSERT INTO `document` (`user_id`,`Doc_Name`,`abstract`)
VALUES ('%d','%s','%s')",'$user_id', '$Doc_Name', '$abstract')
ON DUPLICATE KEY UPDATE
user_id=user_id+'$user_id',
Doc_Name=Doc_Name+'$Doc_Name',
abstract=abstract+'$abstract' "
);
Cargo cult programming? Using sprintf() without any % placeholders is just.... WRONG. As well, why the addition on the updated fields?
MySQL uses concat() for concatenation. + is purely a mathematical operation. Doing 'a' + 'a' does NOT give you aa, you'll get 0.
if user_id is unique field in your table, your query should look like this:
$query = sprintf("
INSERT INTO
`document`(`user_id`, `Doc_Name`, `abstract`)
VALUES
('%s', '%s', '%s')
ON DUPLICATE KEY UPDATE
`Doc_Name` = VALUES(`Doc_Name`),
`abstract` = VALUES(`abstract`)
", $user_id, $Doc_Name, $abstract);
I have a simple INSERT statement which looks like this...
mysql_query("INSERT INTO comments (`user_id`, `profile_id`, `comment`) VALUES ('{$_SESSION['user_id']}', ('$problemID'), ('$comment'))") or die(mysql_error());
Everything is being inserted fine apart from the $problemID variable. In the MySql table it is just returning a 0. The table is set up to receive integers up to 11 characters.
The variable itself is set on a different page but is retrieved using this...
$problemID = intval( $_GET["problem"]);
If I echo the $problemID I get the correct number so I'm unsure as to why it won't just insert this number into my table. Any pointers would be great.
Make sure that your comment is more clearly sanitized; Try something like this:
mysql_query( sprintf(
"INSERT INTO
comments (`user_id`, `profile_id`, `comment`)
VALUES
(%s, %s, '%s')",
intval( $_SESSION['user_id'] ),
intval( $problemID ),
mysql_real_escape_string( $comment )
)) or die( mysql_error() );
Just to be thorough, make sure that your table has a separate primary index (aka entry ID) with auto-increment tacked on. It could be that your MySQL insertion is working fine, however, the receiving table doesn't know that it should keep appending entries.
My hunch is that your INSERT query is referring to the wrong column in your comments table, as you have the following:
INSERT INTO comments (`user_id`, `profile_id`, `comment`)
but you're referring to a variable named $problemID, so my guess is that you meant something like this:
INSERT INTO comments (`user_id`, `problem_id`, `comment`)
Perhaps you copied and pasted the query code but forgot to change the column name in the projection?
Remove the brackets and try to add the variables rather than including them into the string.
mysql_query("INSERT INTO comments (`user_id`, `profile_id`, `comment`)
VALUES ('".$_SESSION['user_id']."', ".$problemID.", '".mysql_real_escape_string($comment)."')") or die(mysql_error());
Sorry, let me try to explain .... recordID auto increments and is my primary key ..... LISTINGID refers to the ID in a different table. In this table 1 need to increment recordListingID for each record that has the same LISTINGID. My insert statement inserts upto 10 records that have the same LISTINGID I need the the recordListingID to start at 1 and so on.
Hi guys
I am inserting records into mysql from php it can be 1 or more records I need one of the cols to increment with the first entry being 1 here is my insert code
mysql_query("INSERT INTO car_listing_images (recordID, recordText, recordListingID, LISTINGID) VALUES ('', '$fileName', '??', '$listingid')");
where I have put ?? is the col that needs to increment. How can i achieve this?
Thanks in advance!
You can use the built in Auto_Increment function of MySql
AUTO_INCREMENT
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
MySql would increment the specified field by 1 (Or what ever interval you set)
You may use user-defined variables
A preface: If you need to have 2 fields that increment, but are not tied to each other, you are probably doing it wrong. It might be better to not have recordListingID and instead just use the recordID as they will probably be the same number.
If your tables are running InnoDB you can create transactions. Then you can try something like this:
<?php
mysql_query('START TRANSACTION');
$recordListingId = mysql_result(mysql_query("SELECT count(*)+1 as num FROM car_listing_images WHERE LISTINGID=$listingid"), 'num', 0);
mysql_query("INSERT INTO car_listing_images (recordID, recordText, recordListingID, LISTINGID) VALUES ('', '$fileName', '$recordListingId', '$listingid')");
mysql_query('COMMIT');
?>
If you don't have innodb, try using a stored procedure.
Alter your table structure to include the AUTO_INCREMENT attribute for your recordListingID column, then omit the column from your insert to have it auto-populate with an incremental number.
I.e: mysql_query("INSERT INTO car_listing_images (recordID, recordText, LISTINGID) VALUES ('', '$fileName', '$listingid')");
You can initialise the variable as 1 and use the post-increment operator:
$value = 1;
for(...){
$sql = 'INSERT ...';
$value++;
}
I don't know if I really understand your question.
If you're wanting to increment a column with every record, it should be defined as an AUTO_INCREMENT column. This way, in your INSERT statement if you insert NULL into that column, it will go up every time.
Alternatively you could do fieldname+1, but AUTO_INCREMENT is always preferred.
As per my comment, you could do something like this:
$row = mysql_fetch_assoc(mysql_query("SELECT MAX(recordListingID) AS `max` FROM car_listing_images"));
$next_id = $row['max'] + 1;
mysql_query("INSERT INTO car_listing_images (recordID, recordText, recordListingID, LISTINGID) VALUES ('', '$fileName', '$next_id', '$listingid')");
I would still seriously recommend against this, it's a much much better implementation to use an AUTO_INCREMENT field.
After your last comment I would suggest the following. You will not be able to do this in MySQL directly (unless you use a variable, but this may go wrong if you're inserting multiple RecordIDs too).
$next_id = 0;
foreach ($insert as $insert_stmt) {
$next_id++;
mysql_query("INSERT INTO car_listing_images (recordID, recordText, recordListingID, LISTINGID) VALUES ('', '$fileName', '$next_id', '$listingid')");
}
i think i know what you were/are trying to accomplish. there may be a better way to it, but what i did was to "select max(id)+1 as nextId from table" and store that in a variable that i used in the secondary id field that you called "recordListingID."
that way the first row you insert will have the same id and recordListingID, but each other row will auto_inc the id, but the recordListingID will be the same as the first.
in my situation, there is only one user doing this at a time, so there is no chance of errors, but in a multi-user situation, you may want to modify this to watch out for people doing inserts at the same time. like maybe marking the last row so your query knows it's finished so you could so something like "select max(id)+1 as nextId from table where lastRow =1" or something like that.