How do I insert using sql when my data is on one table and my where is on another. Here is the code:
$sql = "INSERT INTO user_can (online_id) VALUES ('$online') WHERE user.online = 'online'";
mysql_query($sql);
I seem to be getting errors when trying to insert, the insert does not happen. It looks like I am messing up with my where code. Does anybody know how I can insert my data?
You're mixing parts of one statement type with parts of another. The SQL needs to be something like:
INSERT INTO user_can (online_id) SELECT online_id FROM user WHERE online = 'online';
The INSERT ... VALUES ... format is for providing explicit values in the SQL. Further Information about INSERT syntax.
Related
I am trying to drop a table within a database using SQL injection through PHP.
The PHP code submits a form to the Database with the following command and multi_query($sql):
$sql = "INSERT INTO Student (StdNumber, FName, LName, DOB, PhoneNumber)
VALUES ('$input1', '$input2', '$input3', '$input4', '$input5')";
So I thought, I can SQL Inject input5. So I use:
');"; $sql .= "DROP TABLE IF EXISTS Student;";-- -
This closes the previous sql statement, then I start another statement with 'sql .=' and then I comment off the rest of it with -- -
However the table isn't dropping. I am not seeing my injection command within input5 (PhoneNumber) in the database, so it is successfully closing the previous statement I would believe.
So I am not sure what is wrong, am I using multi_query incorrectly? or is my injection incorrect?
Thank you
Edit 1:
Additionally, when I submit the form it accepts it and makes another entry into the database.
You are trying to manipulate the sql that is generated by the php, not the php itself.
So you should not add php to your 5th input:
');"; $sql .= "DROP TABLE IF EXISTS Student;";-- -
should be something like:
1234567890'); DROP TABLE IF EXISTS Student; -- the rest here will be comments in sql
I have a problem (obviously), the sql query is not successfully inserting into the table;
This is my code:
if (isset($_POST["newpost"])) {
$sqlSTR = "SELECT idPhoto FROM tblhomepagephotos order by idPhoto desc LIMIT 1 INTO #myID;
INSERT INTO tblhomepagetext(idText, hpText)
VALUES (#myID, '" . $_POST["newpost"] . "')";
echo $sqlSTR;
$result= mysql_query($sqlSTR);
}
The echo for the sqlSTR is:
SELECT idPhoto FROM tblhomepagephotos order by idPhoto desc LIMIT 1 INTO #myID;
INSERT INTO tblhomepagetext(idText, hpText) VALUES (#myID, 'Text here')
Now the problem is that it worked perfectly and inserts into tblhomepagetext perfectely when executed from mySQL Workbench, but doesn't work when executed from the website.
Any ideas of why?
I thought it might be due to some PHP conflict where theres the ';' in the sql query.
Your using the INSERT INTO SELECT syntax incorrectly, you have the order swapped around. It should be more like:
INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers
WHERE Country='Germany';
http://www.w3schools.com/sql/sql_insert_into_select.asp
However, I suspect you don't require INSERT INTO SELECT at all. If you simply need to INSERT into a table then the syntax is more like this:
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
http://www.w3schools.com/sql/sql_insert.asp
I suggest you read through those links before proceeding
Edit: Also that semi colon in your example should not be there, that is separating the command in two. This is the reason mySQL workbench can perform the query. It is literally performing two queries sequentially. First it selects some value from your tblhomepagephotos table, then it inserts into tblhomepagephotos. You need to combine the queries as I show above. Then, PHP will be able to perform the single query.
Edit2:
There are many issues with your code its hard to tell whether you need INSERT INTO SELECT or not because I can't figure out your logic.
What I suggest you do is read more examples of howto perform basic CRUD interaction with your database (http://en.wikipedia.org/wiki/Create,_read,_update_and_delete). I suggest you might require to first SELECT your photo details, THEN insert into the tblhomepagetext table. but firstly just see if the below code works. BTW, at very least you should use mysql_real_escape_string() as below when inserting a value via post into your database with mysqli . better yet is to use something like PDO, or learn an entire PHP framework such as Cake, Codeigniter or Zend Framework. These are all solutions to help with exposure to SQL Injection
From your latest comments, here is a solution i think your after:
// PERFORM Base64 PHOTO INSERT QUERY HERE
// (I assume your already doing this as you mention from your Base64 comment.)
// Directly following the insert image query, you need to use the magical command of `mysqli_insert_id()`.
// This will grab the latest inserted Database ID from the previous INSERT command.
$latest_photo_id = mysqli_insert_id();
// now that we have the latest photo ID we can insert into our homepage table
if (isset($_POST["newpost"])) {
$your_id = 1; // put a ID from your photo table here.
$sqlSTR = "INSERT INTO tblhomepagetext(idText, hpText)
VALUES (".$latest_photo_id.", '" . mysql_real_escape_string($_POST["newpost"]) . "')";
echo $sqlSTR;
$result= mysqli_query($sqlSTR);
}
I am having two table consider table1 and table2. I need to do a trigger after inserting into table1.
Trigger has to do some thing like retrieving data from two other tables using select query (it retrieves more than one row) do some calculations with the data retrieved and then it need to insert it into table2 as single row.
I think it's not possible to do these with in a trigger, so I decided to call a php file from that trigger which does all those things. But some persons says calling php from a trigger is not practically good and it has some security risk.
A Simple Example will help you out.
$sql="INSERT INTO `table1` (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
$result = mysql_query($sql) ;
if($result)
{
// Record successfully inserted , place your code which needs to be executed after successful insertion
}
else
{
// Insertion failed
}
I assume you would be using mysqli and not mysql becuase mysql_query is deprecated as of PHP 5.5.0 but this is just an example to help you understand the logic.
Ok got you .. In this case you need to create a TRIGGER something like this.
CREATE
TRIGGER `event_name` BEFORE/AFTER INSERT/UPDATE/DELETE
ON `database`.`table`
FOR EACH ROW BEGIN
-- trigger body
-- this code is applied to every
-- inserted/updated/deleted row
END;
This Question has already been answered check the link below.
MySQL trigger On Insert/Update events
Hope this helps.
I have an html page where I collect an array of values from checkboxes to insert in a database. The html page posts to a PHP page that collects the data and then stores in the database.
For each value, there are a few other fields I would like to include that are the same for all the values such as time entered. I can easily convert the captured array into a comma delimited list using implode. I use such a comma delimited list of ids to update and delete records. However, when I want to insert them, MYSQL does not seem to allow you to use a comma delimited list. My question is, what is the easiest way to insert records, one for each value in the c comma delimited list, without using a loop.
html page
<input type="checkbox" name="var[]" value=1>
<input type="checkbox" name="var{}" value=2>
PHP page
$vars = $_POST['var'];
This gives me an array that I can convert to a comma delimited list using implode.
To delete, I can go
$sql = "DELETE * from table WHERE id in '$vars'";
To update I can go
$sql = "UPDATE table, WHERE id in '$vars'";
But there does not seem to be an equivalent for Insert.
Following would work:
$sql = "INSERT into table (var, timeentered) values (1,now()) (2,now())";
However, that's not how I have my data. what I would like to do is something like
$sql = "INSERT into table (var,timeentered) values($vars), now()" but of course that doesn't work.
Do I have to convert my nice comma delimited list that works so well for update and delete into something that looks like (1,now) (2, now()) for inserting or is there an alternative?
Thanks for any suggestions.
Unfortunately you have to build whole query by yourself:
$sql ="insert into table (var, timeentered) values ";
$sql .= "(".implode(", now()), (", $vars).")";
You need to loop through your data set and create the multi-line insert query manually. There is no other alternative if you want to insert multiple rows with a single query. That is outside of using certain DB frameworks which might present a better interface for doing this. Of course at the end of the day, such a DB framework would in essence be building the multi-item insert query manually at some point.
The question might come done to one of how many items are you going to insert. If you are only going to be inserting a few records at a time, then you might want to consider just using prepared statements with individual inserts. However if you are going to be inserting hundreds of records at a time, that would probably not be a good idea.
In your mysql database you can set the default for the column "time_created" to be a TIMESTAMP default CURRENT_TIMESTAMP. This way you don't have to worry about it. Just use the regular insert and it will automatically set the "time_created" column.
For your other issue of multi-line inserts you can create an $update array and use a foreach loop to issue a sql insert command on every row of data.
Two options I can think of.
Build a dynamic insert query like you suggest. However do not call now() each time but just insert a single date ie
$time = gmdate();
$sql = "INSERT into table (var, timeentered) values (1,$time) (2,$time)";
Or use a prepared statement of the single insert below, turn off autocommit, start a transaction and execute the prepared statement in a for loop for the number of inserts needed, then commit the transaction.
$sql = "INSERT into table (var, timeentered) values (?,?)"
Mostly you will have to build your query using some type of looping structure. Convention and best practice aside if you just want to know how to make your array acceptable for a multiple insert statement then why not just do this:
$values = '('.implode('),(', $array).')';
or if already CSV then:
$values = '('.implode('),(', explode(',' $csv)).')';
then you can just use $values in your query using double quotes.
this the condition: there is a form in html and php haivng around 120 fields its for a website i am making this form on submitting goes to a php page where i first retrive all the values using $_REQUEST[]and then using insert query insert all of them in their specific coloums in the same table in my mysql database. Now i will have to do all the process again for updating these values. Becuase syntax for insert query and update query are quite different .
I dont want to write another 100 lines of code . Is there any way to use the code i wrote inside my insert query to use to update the data.?
Actually in MySQL there is an alternative syntax for insert that is very similar to the syntax for update. You can write
insert customer set customerid=12345, firstname='Fred', lastname='Jones
etc.
Personally I prefer this syntax because it's easy to see what value is going into each field. This is especially true on records with long lists of fields.
On the minus side, it's not standard SQL, so if you ever decide to port your app to a different database engine, all your inserts would have to be rewritten.
Another option I've occasionally used is to write a little function to create your insert and update statements. Then the syntax of your function can be the same, no matter how different the generated code is.
Another alternative, and depending on requirements and keys, you could use:
replace into tbl (<cols>) values (<vals>)
which will insert if not exist, or replace based on keys (insert/update in one query)
or if you are only inserting and don't want to insert twice, you could use:
insert ignore into tbl (<cols>) values (<vals>)
where if the record is already inserted based on keys, it is gracefully ignored
for more info http://dev.mysql.com/doc/refman/5.0/en/replace.html
There is a quite similar syntax for INSERT and UPDATE:
INSERT INTO <table> SET
column1 = value1,
column2 = value2,
...
;
UPDATE <table> SET
column1 = value1,
column2 = value2,
...
WHERE <condition>
;
INSERT INTO yourtable (field1, field2, field3, ...)
VALUES ($field1, $field2, $field3, ...)
ON DUPLICATE KEY UPDATE field1=VALUES(field1), field2=VALUES(field2), etc...
Details on this construct here.