Max(sequence) + 1 (based on my knowledge) should be returning the highest sequence with $_GET['business_id'] in the database + 1 - existing values in the database are 0, 1, and 3 - so max(sequence)+1 should be 4 - so something must be wrong with the line of code. Any ideas?
$insertQuery = "
INSERT INTO owner_business_media
(business_id, sequence, type, filename, title, secret)
VALUES (
'".$_GET[businessid]."',
'(SELECT MAX(sequence)+1 FROM owner_business_media WHERE business_id=".$_GET['businessid'].")',
'$type',
'$fullfile',
'$filename',
'1')
";
Remove single quotes that surround the inner SELECT and instead of the regular INSERT go with INSERT ... SELECT:
$insertQuery = "
INSERT INTO owner_business_media
(business_id, sequence, type, filename, title, secret)
SELECT
'".intval($_GET['businessid'])."',
(SELECT MAX(obm.sequence)+1 FROM owner_business_media obm WHERE obm.business_id=".intval($_GET['businessid']).") AS next,
'$type',
'$fullfile',
'$filename',
'1'
";
Also, never embed a GET variable directly without validating or sanitizing it's contents (see intval($_GET['businessid'])). Otherwise the code gets exposed to SQL injection.
Almost the same as the other answer, yet not completely the same:
$insertQuery = "
INSERT INTO owner_business_media
(business_id, sequence, type, filename, title, secret)
SELECT
'".intval($_GET['businessid'])."',
MAX(sequence)+1 AS next,
'$type',
'$fullfile',
'$filename',
'1'
FROM owner_business_media
WHERE business_id=".intval($_GET['businessid']);
Maybe it would be safer to use IFNULL with sequence (in case the table is empty), like this:
MAX(IFNULL(sequence, 0))+1 AS next
Related
I try to create normalized db.
When I insert values FIRST time, everything is working perfectly, but (I think cause of set values as UNIQUE) it do not want to add.
This is my queries ( I can show database as well if needed )
$query = "INSERT INTO userMore (userEmailG, userGenderG, userAboutG, userBirthdayG, userLanguageG) values ('$userEmailG','$userGenderG', '$userAboutG', '$userBirthdayG', '$userLanguageG');";
$query .= "INSERT INTO userBasic (id_uM, userNameG, userEmailG) values ((SELECT id_uM FROM userMore WHERE userEmailG='$userEmailG'),'$userNameG', '$userEmailG');";
$query .= "INSERT INTO dvlaInfoMore (sixMonthRate, twelveMonthRate, wheelPlan, revenueWeight, typeApproval, taxStatus, taxed, taxDetails, mot, motDetails) values ('$sixMonthRate', '$twelveMonthRate', '$wheelPlan', '$revenueWeight', '$typeApproval', '$taxStatus', '$taxed', '$taxDetails', '$mot', '$motDetails');";
$query .= "INSERT INTO dvlaInfoBasic (id_uDInfoM, plateNumber, make, model, yearOfManufacture, cylinderCapacity, dateofFirstRegistration, co2Emissions, fuelType, colour, vin, transmission)
values (LAST_INSERT_ID(), '$plateNumber', '$make', '$model', '$yearOfManufacture', '$cylinderCapacity', '$dateofFirstRegistration', '$co2Emissions', '$fuelType', '$colour', '$vin', '$transmission');";
$query .= "INSERT INTO userLocation (latitude, longitude, postCode) values ('$latitude', '$longitude', '$postCode');";
$query .= "INSERT INTO userChioce (doWithCar) values ('$doWithCar');";
$query .= "INSERT INTO userStatus (userIdG) values ('$userIdG');";
$query .= "INSERT INTO userMain (userIdG, id_uB, id_uDInfoB, id_uChoice, id_uLoc, id_uStat) values ('$userIdG', (SELECT id_uB FROM userBasic WHERE userEmailG='$userEmailG'), (SELECT id_uDInfoB FROM dvlaInfoBasic WHERE plateNumber ='$plateNumber'), LAST_INSERT_ID(), (SELECT id_uLoc FROM userLocation WHERE postCode='$postCode'),(SELECT id_uStat FROM userStatus WHERE userIdG='$userIdG'))";
So, first time userMore added then userBasic then dvlaInfoMore then dvlaInfoBasic and so one
I set in userBasic column userNameG as UNIQUE, so IF inserted email which already exist, it do not want to go further, BUT if not, everything added correctly.
ALL what I want that it will continue inserting different cars and then by using existing email display result in table userMain.
P.S. if I try to add different car from by using same email address it doesn't work., basically do not add anything.
As you suspected yourself, INSERT with an existing key defined as UNIQUE will fail.
One workaround is to use the REPLACE INTO statement instead of INSERT (see manual).
The SQL statement is as follows:
$sql = "
INSERT INTO usertable
(
userid,,
name,
username,
password,
typeofuser,
dateofaddition,
createdby,
status
)
VALUES (
$userid,
'$empname',
'$username',
'$password',
'$usertype',
'$doa',
'$createdby',
'$radiobt'
)
";
Remove the comma from after userid and correctly include your variables
$sql = "INSERT INTO usertable
(
userid,
name,
username,
password,
typeofuser,
dateofaddition,
createdby,
status
)
VALUES
(
".$userid.",
".$empname.",
".$username.",
".$password.",
".$usertype.",
".$doa.",
".$createdby.",
".$radiobt."
)";
Make sure you prepare this statement before getting it into the DB! (more info: Prepared statement (Wikipedia))
There is a double ,, after userid.
$sql = "INSERT INTO usertable(userid,name,username,password,typeofuser,dateofaddition,createdby,status) VALUES ($userid,'$empname','$username','$password','$usertype','$doa','$createdby','$radiobt')"
Let us take things step by step:
Field names in the query match the field name in the table (they should exactly be the same even the case should match).
What and from where are the values for the varaibles getting generated?
Do the values correspond to the datatype of the fields in the table?
For eg. If there is a variable which expects to receive integer as values and it is made to store strings or characters, mysql is bound to give an error message.
Check for these and let me know.
<html>
<head>
HTML CODE
<?
$username="xxxxxx";
$password="xxxxxx";
$database="xxxxxx";
mysql_connect(localhost,$username,$password);
$escape = "INSERT INTO monster VALUES ('',$_POST["name"],$_POST["soort"])";
$escape2 = "DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL";
$query=mysql_real_escape_string($escape);
$query2=mysql_real_escape_string($escape2);
#mysql_select_db($database) or die("MySQL error: Kan inte ansluta till databasen.");
mysql_close();
?>
</body>
</html>
Every time i run this(from another file, containing the name and soort post's) I get an 500 internal server error. First I figured that the queries may be the problem, but they don't even get executed. However, i tried to escape the queries. But still error.
What is wrong with this code? (note: $escape2 is some code i found that removes duplicates in the database. But i don't really know how to format it so that it can be used through php.)
Use something like below...
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Please do not insert values without escaping.
problem in insert into statement
it should be
$escape = "INSERT INTO monster VALUES ('',".$_POST['name'].",".$_POST['soort'].")";
it is preferable to write colums name while writing insert queries
if column contains string values like VARCHAR or TEXT then use quoted_printable_decode
pass null if column is autoincrement
insert statment
$escape = "INSERT INTO monster (col1, col2, col3) VALUES (NULL,'".$_POST['name']."',".$_POST['soort'].")";
or
$escape = "INSERT INTO monster (col2, col3) VALUES ('".$_POST['name']."',".$_POST['soort'].")";
It looks like you need something like this:
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Also I would suggest to use prepared statements because it is bad experience to build queries.
First of all I have cool proposition for you. What do you say about some advanced PHP? One step further into great world of safe PHP + MySQL apps?
Introducting to you a PDO. (I know this is not answer to your question but you can consider it). Example of use on your queries:
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$insertQuery = $db->prepare('INSERT INTO monster VALUES ("", :name, :soort)');
$deleteQuery = $db->prepare('DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL');
//to execute query:
$deleteQuery->execute();
//or with params:
$insertQuery->execute(array(
':name' => $_POST['name'],
':soort' => $_POST['soort'],
));
Cool, huh? There is more... Now according to your problem it could be everything (as we don't have error log) but my guess is:
Try to use <?php instead of <?
$escape = "INSERT INTO monster VALUES ('',{$_POST["name"]},{$_POST["soort"]})";
EDIT:
As you provided error log - now I'm sure that problem is in $escape query. It's because you used $escape = " <- and then $_POST["name"] so there was a collision of " (if I can say so).
Try this:
Whenever you insert string type of values in the database using query it has to pass in the quote format. So you just need to change your insert query here.
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
write query like this.
-
Thanks
I am confused, I don't know what's wrong. I'm about to transfer all data from my first table to the other. Here is my code:
$getdata = mysql_query("SELECT Quantity, Description, Total FROM ordercart");
while($row = mysql_fetch_row($getdata))
{
foreach($row as $cell){
$query1 = mysql_query("INSERT INTO ordermem (Quantity, Description, Total) VALUES
($cell)",$connect);
}
mysql_free_result($getdata);
}
I get the error: Warning: mysql_fetch_row(): 5 is not a valid MySQL result resource.
You only pass one value in the INSERT, which expects three values to be passed to the fields Quantity, Description, Total:
INSERT INTO ordermem (Quantity, Description, Total) VALUES
($cell);
Change it to:
INSERT INTO ordermem (Quantity, Description, Total) VALUES
($cell, $descriptionParam, $totalParam);
You may also try to use INSERT INTO SELECT directly instead of two distinct statements like so:
INSERT INTO ordermem (Quantity, Description, Total)
SELECT Quantity, Description, Total FROM ordercart;
You are trying to insert 1 value into 3 fields. You need to have 1 value for each field. For example:
$quantity="$_GET['qty']";
$description="$_GET['desc']";
$total="$_GET['total']";
$query = mysql_query("INSERT INTO ordermem (Quantity, Description, Total)
VALUES ('$quantity','$description','$total'))
Use debugging to find out the source of your problem.
mysql_query() returns a boolean value that tells you whether the operation succeeded or not. If it did not succeed, the mysql_error() function give you mySQL's error message.
Example:
$query1 = mysql_query("INSERT INTO ordermem (Quantity, Description, Total) VALUES ($cell)",$connect);
if (!$query1)
trigger_error("mySQL Error: mySQL returned ".mysql_error(), E_USER_ERROR);
This will give you a message something like "Number of values does not match the number of columns", which gives you a hint about what's wrong.
Try this :
$query = "INSERT INTO ordermem (Quantity, Description, Total) SELECT Quantity, Description, Total FROM ordercart";
mysql_query($query);
i have a form where i post the data to mysql. the query should insert the data from the form into table1, but also include data from another table2 where the ID that is send from the form is equal to the ID in table2?
i use the old mysql connection, i know, not the best :-) and php!
hope someone can help, thanks :-)
Martin
think maybe I should give some more info :-)
table1 is called: books
from the form, i have the following value: itemCode, itemQty, ownerID
i have 2 static value: status, type
the values from table2 that must be inserted into table1 is:
title, description, price, frontcover
from table2 the field isbn should be equal to itemCode from form.
here is what i have tried so far:
$bookid=$_POST['itemCode'];
$itemQty=$_POST['itemQty'];
$status='2';
$ownerID = $user->id;
$query="INSERT INTO books (name, description, price, picture, status, ownerID, itemqty, type, studie, isbn) SELECT (title, description, price, frontcover FROM isbnbooks WHERE isbn=$itemCode), $status, $ownerID, $itemQty, '1', '1', $bookid)";
UPDATE:
I have also tried this one here:
$bookid=$_POST['itemCode'];
$itemQty=$_POST['itemQty'];
$status='2';
$ownerID = $user->id;
$data2 = mysql_fetch_array (mysql_query("SELECT * FROM isbnbooks WHERE isbn = $bookid"));
$title = $data2[title];
$description = $data2[description];
$price = $data2[price];
$picture = $data2[frontcover];
$query="INSERT INTO books (name, description, price, picture, status, ownerID, itemqty, type, studie, isbn)
VALUES ($title, $description, $price, $picture, $status, $ownerID, $itemQty, '1', '1', $bookid)";
mysql_query($query) or die("Opps some thing went wrong");
If you have values 'a' and 'b' to go into columns f1 and f2 of table1; and in f3 you want the value of table2.field where table2.id is 123, you can prepare and execute a SQL statement along these lines:
INSERT INTO table1 (f1, f2, f3)
SELECT 'a', 'b', field FROM table2 WHERE id = 123;
Further to seeing the code in your updated question, the problem with your first attempt is that you're trying to mix INSERT ... SELECT with INSERT ... VALUES; sadly they are mutually exclusive. However, you could write instead:
INSERT INTO books (
name,
description,
price,
picture,
status,
ownerID,
itemqty,
type,
studie,
isbn
)
SELECT
title,
description,
price,
frontcover,
:status, -- use prepared statements to prevent SQL injection
:ownerID, -- see http://bobby-tables.com/ for more info
:itemQty,
'1', -- do you really want a string containing a number?
'1',
:bookid
FROM isbnbooks
WHERE isbn=:itemCode;
Your second attempt looks as though it ought to work (although you really should use prepared statements, see above!); what problems are you having with it?
in the absence of code, here's the workflow id recommend:
Form is submitted -> check and sanitize values - > execute lookup query against "table 2" and get your related values -> commit the update query with both form and "table2" data -> on successful update, notify user that their information was processed -> thank them.
Something like this ? :
$data2 = mysql_fetch_array (mysql_query("SELECT * FROM table2 WHERE id2 = '1'"));
$data1 = data2['column2'];
mysql_query("INSERT INTO table1 VALUES('value1','$data2') WHERE id1 = id2);