I need to insert data from a table named wishlist into another table (wishlisturi_salvate) and altough the insert looks ok, something doesn't work right and no inseration is being made.Thanks for the help, I really appreciate it.
<?php
session_start();
include ('conex.php');
$sel2="select id_wishlist from wishlisturi_salvate";
$que2=mysql_query($sel2);
while($rez2=mysql_fetch_array($que2))
{
$a=$rez2['id_wishlist'];
}
$id_wishlist=$a;
echo $id_wishlist;
$sel="SELECT * from wishlist";
$que=mysql_query($sel);
while ($rez=mysql_fetch_array($que))
{
$insert="INSERT INTO 'wishlisturi_salvate'('id_user', 'id_wishlist', 'id_produs', 'nume_produs', 'pret_produs', 'cantitate_produs', 'suma')
VALUES('".$_SESSION['id']."','".$id_wishlist."','".$rez['id_produs']."','".$rez['nume_produs']."','".$rez['pret_produs']."','".$rez['cantitate_produs']."','".$rez['suma']."')";
if(!mysql_query($insert)) echo "fml";
echo "<br>".$insert;
}
if(mysql_query($insert))
{
header("location:user.php");
}
else echo "Nu s-a facut inserarea";
?>
No insertion is being made most likely because of the errors inside the query:
Right of the bat, there is already an error:
INSERT INTO 'wishlisturi_salvate'('id_user', 'id_wishlist', 'id_produs', 'nume_produs', 'pret_produs', 'cantitate_produs', 'suma')
The proper quoting of table/column names must be backtickts, not single quotes
INSERT INTO `wishlisturi_salvate` (`id_user`, `id_wishlist`, `id_produs`, `nume_produs`, `pret_produs`, `cantitate_produs`, `suma`)
Or just omit them, its okay in this case.
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Sidenote:
If you haven't already, always turn on error reporting:
error_reporting(E_ALL);
ini_set('display_errors', '1');
First of all I'll rcomend you to use PDO or mysqli instead of mysql to avoid SQL injection.
Anyway, if you want to insert elements from one table to another one I recommend you to use an insert statment with a subselect. That way it'll be faster and you will waste less memory.
Not an answer, more of an observation ; It will be far more efficient to loop through your results to build up a single SQL insert multiple statement that you send to the db once.
$insert = "INSERT INTO 'wishlisturi_salvate'('id_user', 'id_wishlist', 'id_produs', 'nume_produs', 'pret_produs', 'cantitate_produs', 'suma') VALUES ";
foreach( of your results ){
$insert .= "(x,y,z,a,b,c,d),";
}
// now trim off last comma, then send to db.
// or create an array then join it to the $insert
Same info can be read here : http://www.electrictoolbox.com/mysql-insert-multiple-records/
Related
The PHP code I have inserts the HTML form data from the previous page into the database and in the same SQL statement return the PostID back from the inserted data. The PostID column is AUTO_INCREMENTING. I have been researching this problem for a week or two now and have found no significant solutions.
<?php
include("dbconnect.php");
mysql_select_db("astral_database", $con);
session_start();
$username = $_SESSION['username'];
$forumtext = $_POST["forumtext"];
$forumsubject = $_POST["forumsubject"];
$postquery = 'INSERT INTO Forums (Creator, Subject, Content) VALUES ("$username", "$forumsubject", "$forumtext"); SELECT LAST_INSERT_ID()';
$result = mysql_query($postquery, $con);
if (!$con) {
echo "<b>If you are seeing this, please send the information below to astraldevgroup#gmail.com</b><br>Error (331: dbconnect experienced fatal errors while attempting to connect)";
die();
}
if ($username == null) {
echo "<b>If you are seeing this, please send the information below to astraldevgroup#gmail.com</b><br>Error (332: Username was not specified while attempting to send request)";
die();
}
if ($result != null) {
echo "last id: " . $result;
$fhandle = fopen("recentposts.txt", "r+");
$contents = file_get_contents("recentposts.txt");
fwrite($fhandle, json_encode(array("postid" => $result, "creator" => $username, "subject" => $forumsubject, "activity" => time())) . "\n" . $contents);
fclose($fhandle);
mysql_close($con);
header("location: http://astraldevgroup.com/forums");
die();
} else {
die("<b>If you are seeing this, please send the information below to astraldevgroup#gmail.com</b><br>Error (330: Unhandled exception occured while posting forum to website.)<br>");
echo mysql_error();
}
mysql_close($con);
?>
First off, the mysql_query doesn't return anything from the SELECT statement. I haven't found anything that will properly run both the SELECT statement and the INSERT statement in the same query. If I try running them in two different statements, it still doesn't return anything. I tried running the following statement in the SQL console and it ran perfectly fine without errors.
INSERT INTO Forums (Creator, Subject, Content) VALUES ("Admin", "Test forum 15", "This is a forum that should give me the post id."); SELECT LAST_INSERT_ID();
The mysql_query function does not run multiple statements
Reference: http://php.net/manual/en/function.mysql-query.php
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server ...
That's one reason your call to mysql_query isn't returning a resultset.
The most obvious workaround is to not try to run the SELECT in the same query. You could use a call to the mysql_insert_id instead.
Reference: PHP: mysql_insert_id http://php.net/manual/en/function.mysql-insert-id.php
Answers to some of questions you didn't ask:
Yes, your example code is vulnerable to SQL Injection.
Yes, the mysql_ interface has been deprecated for a long time.
Yes, you should being using either PDO or mysqli interfaces instead of the deprecated mysql_ functions.
FOLLOWUP
Re-visiting my answer, looking again at the question, and the example code.
I previously indicated that the code was vulnerable to SQL Injection, because potentially unsafe values are included in the SQL text. And that's what it looked like on a quick review.
But looking at it again, that isn't strictly true, because variable substitution isn't really happening, because the string literal is enclosed in single quotes. Consider what the output from:
$foo = "bar";
echo '$foo';
echo '"$foo"';
Then consider what is assigned to $postquery by this line of code:
$postquery = 'INSERT ... VALUES ("$username", "$forumsubject", "$forumtext")';
Fixing that so that $username is considered to be a reference to a variable, rather than literal characters (to get the value assigned to $username variable incorporated into the SQL text) that would introduce the SQL Injection vulnerability.
Prepared statements with bind placeholders are really not that hard.
$result will never be null. It's either a result handle, or a boolean false. Since you're testing for the wrong value, you'll never see the false that mysql_query() returned to tell you that the query failed.
As others have pointed out, you can NOT issue multiple queries in a single query() call - it's a cheap basic defense against one form of SQL injection attacks in the PHP mysql driver. However, the rest of your code IS vulnerable other forms of injection attacks, so... better start reading: http://bobby-tables.com
Plus, on the logic side, why are you testing for a null username AFTER you try to insert that very same username into the DB? You should be testing/validating those values BEFORE you run the query.
<?php include_once("database.php");
?>
<?php include_once("header.php");
?>
<?php
if ($_POST['submit'] )
{
$food_name = $_POST['food_name'];
$food_calories = $_POST['food_calories'];
echo $food_name . $food_calories;
if (!empty($food_name) && !empty($food_calories) )
{
$query = 'INSERT INTO foods VALUES(0, $food_name, $food_calories)';
mysqli_query($con, $query) or die(mysqli_error($con));
echo 'added';
} else {echo'fail';}
} else {echo'fa2oo';}
?>
<h1> Please Fill out Form Below to Enter a New Food </h1>
<form action="addfood.php" method="post">
<p>Name:</p>
<input type="text" name="food_name"/>
<p>Calories:</p>
<input type="text" name="food_calories"/> </br>
<input type="submit" value="submit" />
</form>
<?php include_once("footer.php")?>
Really don't understand why this simple insert is not working. The form is self-referencing. The form does not echo anything and simply resets when i hit the submit button. database connects with no errors.
Since you're inserting strings, you need to enclose them by single quotes ('):
$query = "INSERT INTO foods VALUES(0, '$food_name', $food_calories)";
Note, however, that building an SQL statement by using string manipulation will leave your code vulnerable to SQL inject attacks. You'd probably be better off using a prepared statement.
You have a few errors in your code:
1. Missing name attribute
You are missing the name attribute for your submit button. So add it like this:
<input type="submit" name="submit" value="submit" />
//^^^^^^^^^^^^^
2. Wong variables in empty()
You have to check if the $_POST variables are empty! Otherwise you would try to assign an undefined variable to another variable. So change your second if statement to this:
if (!empty($_POST['food_name']) && !empty($_POST['food_calories']) )
//^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
And also put the assignments inside the second if statement.
$food_name = $_POST['food_name'];
$food_calories = $_POST['food_calories'];
3. Wrong quotes + missing quotes
You have to use double quotes that your variable in the query gets parsed as variables. Also you have to put single quotes around them since they are strings, so change your query to this:
$query = "INSERT INTO foods VALUES(0, '$food_name', '$food_calories')";
//^ ^ ^ ^ ^
Side notes:
Add error reporting at the top of your file(s) to get useful error messages:
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?>
You may also want to change to mysqli with prepared statements since they are, much safer.
Here's the safe way of doing this using mysqli. Prepared statements will make sure you don't have (as high of) a risk of SQL injection
editing to include the connection:
$conn = new mysqli($host, $username, $password, $dbname);
If you want to see errors, you need to tell php to give the the errors. this should suffice:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
This part is how to do the query.
Note the bind_param part; this is where you identify how your variables are going to into the database, and what datatype they need, so you don't need to remember which items to put in quotes in the actual query.
$query = $conn->prepare("INSERT INTO foods VALUES(0, ?, ?)");
$query->bind_param("si",$food_name, $food_calories);
$query->execute();
$query->close();
As mentioned before, $food_name is a string, so you specify it as such with the s in the bind_param and assuming that calories are an integer, they go in as i.
Another nice feature of using this approach is you no-longer need to worry about escaping variables; items in inputs go in exactly as they are entered
If you want more information in detail there's always this reliable source:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
If you find this a bit too much, here's a great site to learn step by step how to use prepared statements from scratch (it also includes PDO but you may find it easier to use the mysqli at first and it still pretty good). http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Have fun!
There are a few things wrong here.
Firstly, anything inside this conditional statement will not happen because of your submit button not bearing the "submit" name attribute.
if ($_POST['submit'] ){...}
However, it's best using an isset() for this.
if (isset($_POST['submit'] )) {...}
Modify your submit to read as:
<input type="submit" name="submit" value="submit" />
^^^^^^^^^^^^^
Then, we're dealing with strings, so wrap the variables in your values with quotes.
Wrap your query in double quotes and the values in single quotes:
$query = "INSERT INTO foods VALUES (0, '$food_name', '$food_calories')";
Sidenote #1: If you experience difficulties, use the actual column names in which they are to go inside of.
I.e.: INSERT INTO table (col1, col2, col3) VALUES ('$val1', '$val2', '$val3')
Sidenote #2: Make sure that 0 for your column is indeed an int, however I don't know why you're using that.
If that column is an auto_increment, then replace the 0 with '' or NULL, should your schema accept it.
Now, should there be any character that MySQL may complain about, being quotes, etc., then you will need to escape/sanitize your data.
Say someone entered Tim's donuts in an input:
MySQL would translate that in your values as 'Tim's donuts', in turn throwing a syntax error.
Using mysqli_real_escape_string() for instance, would escape the apostrophe and render it as 'Tim\'s donuts' being a valid statement since it has been escaped.
Better yet, using prepared statements, as outlined below.
In its present state, your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Footnotes:
Given that we don't know which MySQL API you are connecting with, please note that different APIs do not intermix with each other.
For example:
You can't connect using PDO and querying with mysqli_
You can't connect using mysql_ and querying with mysqli_
etc. etc.
You must be consistent from A to Z, meaning from connection to querying.
Consult Choosing an API on PHP.net
https://php.net/mysqlinfo.api.choosing
Final closing note(s):
As stated by Rizier123, you are best using:
if (
!empty($_POST['food_name'])
&&
!empty($_POST['food_calories'])
)
It is a better solution.
Your issue (at least one of them) might be the SQL statement itself. Depending on the columns that you have in this foods table, you'll be required to specify the columns that you're inserting into. Try this:
INSERT INTO foods (col1, col2, col3) VALUES (val1, val2, val3)
Also, if val1 is supposed to be the ID column, you can't specify a value for that if it's auto-incrementing... the db will take care of that for you.
I have some PHP code and I'm trying to insert or to update data in a MySQL table.
The insert query works, but the update query doesn't. The values are printed correctly at the end.
<?php
$nm=$_GET["nm"];
$reg=$_GET["regno"];
$con=mysql_connect("localhost","root","admin");
mysql_select_db("Q14",$con);
// $res=mysql_query("insert into stdtable values('$nm','$reg')",$con);
$res=mysql_query("UPDATE stdtable SET `NAME`='$nm',`REG NO`='$reg' WHERE
'REG NO'='$reg'",$con);
echo "SUCCESS";
echo $nm.$reg;
?>
Here:
'REG NO'='$reg'",$con);
you've used ', but has to be `
For REG NO (in where clause) you have to use backticks not single quotes. Or better rename the column, without blanks in the name:
$res=mysql_query("UPDATE stdtable SET `NAME`='$nm',`REG NO`='$reg' WHERE
`REG NO`='$reg'",$con);
Do not longer use deprecated mysql_* API. Use mysqli_* or PDOwith prepared statement.
I'm trying to loop data from a api and then post these values to a MySQL db.
something like this:
$values = json_decode(file_get_contents("my-json-file"));
$SQL = new mysqli(SQL_HOST, SQL_USER, SQL_PASS, DB_NAME);
$SQL->autocommit(FALSE);
foreach($values As $item)
{
$query = "INSERT INTO my_table VALUES ('".$item->value1."', '".$item->value2.";)";
$SQL->query($query);
if(!$SQL->commit())
{
echo "ERROR ON INSERT: [" . $query . "]<hr/>";
}
}
$SQL->close();
Since the loop is too fast, the SQL can't catch up. (Yea!)
I would then need something like this:
foreach($values As $item)
{
/**** STOP/PAUSE LOOP ****/
$query = "INSERT INTO my_table VALUES ('".$item->value1."', '".$item->value2.";");
$SQL->query($query);
if($SQL->commit())
{
/**** START THE LOOP AGAIN ****/
}
else
{
echo "ERROR ON INSERT: [" . $query . "]<hr/>";
}
}
Or how should I do this the right way?
EDIT: It inserts random posts every time.
EDIT 2: This is just example code. It does escape and all that, and yes the semi colon is wrong here but since so many commented on it i will not change it. This was not the problem in the real case.
I tried to run it on another server and there it worked. The problem was fixed by restarting MAMP.
Firstly, your idea that the loop runs too fast for MySQL to keep up is completely totally wrong. The $SQL->query() call will wait for the MySQL to return a response before proceeding, so the loop won't run any faster than MySQL is responding.
Now onto the actual problem.... your query:
$query = "INSERT INTO my_table VALUES ('".$item->value1."', '".$item->value2.";)";
There's a semi-colon in there at the end, after value2 which is invalid. I guess you intended to type a quote mark there? The semi-colon will be causing all your queries to fail and throw errors.
This may be the cause of your problem but you haven't got any error checking in there, so you won't know. Add some error checking to your code after calling the query; even if the query is right, it's still possible to get errors, and your code should check for them. See the examples on this manual page: http://www.php.net/manual/en/mysqli-stmt.error.php
Finally, since you're using the mysqli API, it's worth mentioning that your code would be a lot better and probably more secure if you used prepared statements. See the examples in PHP manual here: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
[EDIT]
Another possible reason your query is failing is that you're not escaping the input values. If any of the input values contains a quote character (or any other character that is illegal in SQL) then the query will fail. In addition, this problem makes your code vulnerable to a SQL injection hacking attack.
You need to escape your input using $SQL->real_escape_string() OR by changing your query to use prepared statements (as recommended above).
Your query is inside the loop, which means that the loop will wait until your query finished executing before it continue, php code is processed in order...
Has #phpalix said, PHP goes in order, and waits for the previous action to finish.
I think you SQL is wrong. Try replacing your INSERT with this:
$query = "INSERT INTO my_table VALUES ('".$item->value1."', '".$item->value2."');";
And don't forget to run at least mysql_real_escape_string for each variable, for security measures.
As many of the answers and comments say, it does not continue until the SQL is done. The problem was in my local apache/mysql server. It was fixed by restarting it. Yes, stupid post.
If we can't use PDO or mysqli (for any reason), is this method safe for INSERT and SELECT?
<?php
if (!empty($_POST[id]) && !empty($_POST[name])) {
require_once ( 'config.php' );
// SAFE INTVAL ID
$id = intval($_POST[id]);
$connect = mysql_connect("$server", "$user", "$password")
OR die(mysql_error());
mysql_select_db("$database", $connect);
// ESCAPING NAME
$name = mysql_real_escape_string($_POST[name]);
$query = "INSERT INTO table (id, name) VALUES ('$id', '$name')";
$result = mysql_query($query, $connect);
if (!$result) { echo 'success'; } else { echo 'fail'; }
}
?>
cause i've read many times never to use mysql_query,
is it dangerous even if we are careful and escape in time?
As per my knowledge, your query is perfectly fine.
You are escaping the SQL with
mysql_real_escape_string($_POST[name])
This adds additional security to your code.
The only suggestion is that use:
$_POST['name']
instead of
$_POST[name]
As it will generate PHP warning.
Thanks.
To add to the other answers, it's "safe", as in the query can't be exploited. The one thing to watch out for though is that you're trusting your users to provide you with an ID (which I assume here is your primary key). Of course, this means that your users can overwrite other records.
A better way would be to omit the id column (and its value) from your query, and mark the column as AUTO_INCREMENT when creating the table. Any omitted value from a query becomes its default value, which in this case will normally be the last value of id+1.
Even though you say you can't use them, possibly because they're too complicated (?), you really should doing a little research and understanding how to use them. I promise that once you do, you won't even want to go back! :) I recommend using PDO / MySQLi because PHP 5.5 is depreciating MySQL and you'll get E_DEPRECIATED notices.
Prepared statements using MySQLi or PDO mean that you don't have to escape any strings, you simply refer to each variable with a ?, and then state later on what datatype the ? has s being string, for example.
You wouldn't need to use mysql_real_escape_string() then. Future proof your code! :)