Can't Get Simple SQL Insert to Work - php

<?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.

Related

Why does my code not insert the data into the database?

<?php
require 'connect.inc.php';
$food= $_POST['food'];
$cost= $_POST['cost'];
$sqlinsert = "INSERT INTO test (eat, pay) VALUES ('$food','$cost')";
?>
<form method = "POST" action = "index.php">
Food: <input type = "text" name = "food">
<br/>
Cost: <input type = "text" name = "cost">
<br/>
<input type = "submit" value = "order">
</form>
Why does my code not work? index.php is fine, it connects well, but no output is shown in my database when I run this code.
You appear to be new at databases, seeing your other questions and this being the only one related to doing db work.
This line never gets executed:
$sqlinsert = "INSERT INTO test (eat, pay) VALUES ('$food','$cost')";
We don't know which MySQL API you are using to connect with; if it's mysql_, or mysqli_ or PDO, or other since you did not mention that in your question.
Depending on the API used, you need to run mysql_query(), or mysqli_query() or query()/execute() in PDO.
Consult the following links on how to do this:
http://php.net/manual/en/function.mysql-query.php
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/pdo.query.php / http://php.net/manual/en/pdostatement.execute.php
Check for errors also using the same API you connected with, and seeing that you're more than likely running this code inside the same file, you need to use a conditional statement around your POST arrays to check if they're empty, and/or use an isset() on the submit button and giving it a "name" attribute.
I.e.: <input type = "submit" name = "submit" value = "order">
with if(isset($_POST['submit'])) {...}
Otherwise, you stand at getting errors thrown back.
If empty reference:
http://php.net/manual/en/function.empty.php
Note: Different MySQL APIs do not intermix, so you can't connect with mysql_ and query with mysqli_query() or PDO, keep this in mind.
Another thing is to make sure that data going into the database doesn't contain characters that MySQL will complain about such as apostrophes.
Therefore you will need to escape that data. This is good for another reason, avoiding a possible SQL injection; you should use a prepared statement for it.
References:
https://en.wikipedia.org/wiki/SQL_injection
https://en.wikipedia.org/wiki/Prepared_statement
Footnotes:
If you are using the mysql_ API to connect with, that API is deprecated and has been removed in PHP 7.0. If this is the case, then you will need to use either the mysqli_ or PDO API.

Insert into database using a while loop

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/

insert value of html select form into mysql database

I want to insert the value of a selected 'select form' into my mysql database.
How can i get the right value of this?
<form action='' method='post'>
<select name="myselectbox">
<option name="myoption1" value="myoption1">myoption1</option>
<option name="myoption2" value="myoption2">myoption2</option>
<option name="myoption3" value="myoption3">myoption3</option>
<option name="myoption4" value="myoption4">myoption4</option>
</select>
<input type='submit' value='submit'/>
</form>
something like that? (this one didn't work obviously..)
$sql = "INSERT INTO Entries (myoption1) VALUES ('$_POST[myselectbox]')";
you have to wrap your select tag into a form tag .
<form action='' method='post'>
<select name="myselectbox">
<option name="myoption1" value="myoption1">myoption1</option>
<option name="myoption2" value="myoption2">myoption2</option>
<option name="myoption3" value="myoption3">myoption3</option>
<option name="myoption4" value="myoption4">myoption4</option>
</select>
<input type='submit' value='submit'/>
</form>
once you submit the form, you will get the post variable as $_POST['myselectbox'] that could be appended into a mysql query as you have already did. but for a better way dont just append it like that but check the form is submitted and post variables are available or not before appending.
eg:
if(!empty($_POST['myselectbox'])){
/*.. do your query section... */
}
you have error in your SQL command, $_POST needs html names to be wrapped in quotes like => $_POST['some_name'] :
$sql = "INSERT INTO Entries (myoption1) VALUES ('$_POST[myselectbox]')";
/* ^^ missing quotes here*/
try it this way :
$sql = "INSERT INTO Entries (myoption1) VALUES (".$_POST['myselectbox'].")";
Assuming that your form is correct and it is posting the values that you want to your script.
(You have sprinkled your code with echo to ensure this is the case?)
The simplest reliable way of sending the data into a SQL statement and therefore into mysql is to use prepared statements.
Take a look here: http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
Basically you write the SQL statement without your variables in it (replaced with ?) and then tell mysql to execute the statements with your variables later. It avoids the need to escape strings and worry about how to build things up.
As an example, you might have:
// Connect to mysql
$mysqli = new mysqli('where your server is', 'my_user', 'my_password', 'world');
// Build the initial statement - easier to read as you don't have your string concatenation here
$stmt = $mysqli->prepare( "INSERT INTO Entries (myoption1) VALUES (?)" );
// Tell mysql that the '?' should be replaced with the value in your post array
$stmt->bind_param( "s", $POST['myselectbox'] );
// Execute the statement
$stmt->execute()
Obviously you should add error handling too, but the documentation covers the basics of this.
SQL Injection
The main reason why the use of prepared statements is a good idea is that it avoids SQL injection attacks.
There are other ways round, but in my mind this is the simplest solution.
SQL Injection attacks are situations where someone attempts to change the SQL statement that is being run by "injecting" other SQL into your statement.
Using your code as an example, you may execute this statement:
$sql = "INSERT INTO Entries (myoption1) VALUES ('". $_POST['myselectbox'] ."')";
Which would normally receive (let's suggest) something like myoption1.
This would result in the SQL being:
INSERT INTO Entries (myoption1) VALUES ('myoption1');
If someone decided to, they could send '='' OR '1'='1
This would result in the SQL being:
INSERT INTO Entries (myoption1) VALUES (''='' OR '1'='1');
Which is (obviously) very different.
Or, even worse send '=')'; DROP TABLE Entries WHERE (''='
This would result in the SQL being:
INSERT INTO Entries (myoption1) VALUES (''=''); DROP TABLE Entries WHERE (''='');
Use Prepared Statements
Simply put, but using prepared statements, you are telling mysql that what you are sending is a literal string to be used as a parameter. It can never be regarded as part of the statement itself and therefore the above is simply not possible.
Much much safer.
I hope that makes it clearer. If you want more info I suggest you research it independently...
$value = mysql_real_escape_string($_POST['myselectbox']);
$sql = "INSERT INTO Entries (myoption1) VALUES ($value)";

Add row in MySQL database

I am pretty new with databases and SQL, and I am learning to program. I have a table like this. I use phpMyAdmin.
I have to fill a form and when I click the button submit, I must add some datas in this database called "europe".
<form action="addtime.php" method="POST">
//html table
<p align="center"><input value="Send record" type="submit"></p>
</form>
And here you can see addtime.php:
<?php
$con=mysqli_connect("localhost","username","password","my_mk7vrlist");
mysql_query(INSERT INTO europe (Num,playername,Friendcode,Country,Skype,Twitter,Youtube) VALUES (3, "kjghskj", "t4glofshgk", "es", "jgd", "49hfis", "vvvv44444"));
mysqli_close($con);
?>
The database name is my_mk7vrlist and the table name is europe. I have an error that says "unexpected T_STRING on line 22". On that line there is the function mysql_query();.
What am I missing?
mysqli_query("INSERT INTO...
might require the db $link:
mysqli_query($con, "INSERT INTO...
Put your query inside quotes. Becareful with single / double quotes.
<?php
$con=mysqli_connect("localhost","usernale","password","my_mk7vrlist");
mysqli_query($con, 'INSERT INTO europe (Num,playername,Friendcode,Country,Skype,Twitter,Youtube) VALUES (3, "kjghskj", "t4glofshgk", "es", "jgd", "49hfis", "vvvv44444")');
mysqli_close($con);
And change the mysql_query to mysqli_query (Procedural style)
It's been a bit since I've dealt with PHP but this should work (make appropriate changes to the username, password and database fields; I removed the name of the database to force you to re-write it, in case it's actually spelled wrong):
<?php
$con = mysqli_connect('localhost', 'user_name', 'password', 'database');
mysqli_query($con, "INSERT INTO europe (Num, playername, Friendcode, Country, Skype, Twitter, Youtube) VALUES (3, 'kjghskj', 't4glofshgk', 'es', 'jgd', '49hfis', 'vvvv4444'");
mysqli_close($con);
?>
I'd suggest the following though:
<?php
$db_con = mysqli_connect('localhost', 'user_name', 'password', 'database');
$db_query = "INSERT INTO europe"
. " (Num, playername, Friendcode, Country, Skype, Twitter, Youtube)"
. " VALUES (3, 'kjghskj', 't4glofshgk', 'es', 'jgd', '49hfis', 'vvvv4444'";
mysqli_query($db_con, $db_query);
mysqli_close($db_con);
?>
In short, as others have mentioned, when you're passing your SQL to the mysql_query and mysqli_query functions, it needs to be a String data type (Either double or single quoted).
In this example you don't need double quotes, but I'd suggest you make it a habit, because typically when working with databases you're not going to be passing raw values like the above; you're going to be passing variables into the string, which a double quote allows (a single quoted string does not make that check in PHP). Take this into account, because your original code had your connection variables encapsulated in double quotes; this means that PHP's interpreter is going to make pass to check for variables first, and then interpret the actual string.
However, what others left out (when I began writing this) is that you're writing procedurally and not utilizing the mysqli object; this requires you to pass a connection variable to the mysqli_query as well, otherwise how is it going to query the data?
So, this is why $db_con is the first argument, and $db_query is the second. For reference, you could also do this (as an object):
<?php
$db = new mysqli('localhost', 'user_name', 'password', 'database');
$db_query = "INSERT INTO europe"
. " (Num, playername, Friendcode, Country, Skype, Twitter, Youtube)"
. " VALUES (3, 'kjghskj', 't4glofshgk', 'es', 'jgd', '49hfis', 'vvvv4444'";
$db->query($db_query);
$db->close();
?>
I also suggest instead of using the variable name "con", use something less ambiguous like "db_con" because someone who sees the variable name, and only the variable name, will not typically know what "con" means; with a "db" prefix, they could more easily infer this is a database connection variable.
"Unexpected T_STRING" from what I can recall is sort of an asinine error (it can mean a number of things), but typically it suggests a syntax error; for example, missing brackets, missing semicolon, missing quotes, et cetera. Typically you look at the beginning of the line it mentions or before it; I mention this because I can't assume that line 22 is the only error, unless PHP has come very far forward in it's error protocols.
Additionally, I broke your declaration into two parts; a query variable, and the query function call. This is, again, semantics and unnecessary, but you'll find it easier to maintain and read this way. I broke the query variable into separate lines to highlight important logical shifts in the SQL query. Again this is unnecessary now, but important to take into account for future cases when your queries get more complex (especially when working with joins).
Furthermore, I'd suggest your field names stay consistent; I noticed "playername" is not capitalized, and the others are capitalized. I'd suggest keeping them all lowercase and to separate inner words with "_". Consistency is more important than your code as most time goes into debugging than actual programming.
I apologize if anything is off point or if they're any errors (I'll make edits if necessary), it has been a while since I've worked with PHP.
References:
http://www.php.net/manual/en/mysqli.query.php
Rewrite your query like this
mysql_query("INSERT INTO `europe` (`Num`,`playername`,`Friendcode`,`Country`,`Skype`,`Twitter`,`Youtube`) VALUES (3, 'kjghskj', 't4glofshgk', 'es', 'jgd', '49hfis', 'vvvv44444')");
Also, stop using mysql_* functions as they are deprecated. Switch to MySQLi or PDO instead.
"usernale" are you it`s right? Maybe "username" and add a quotes '' in your query
Your sql query is a string, so enclose it properly:
"INSERT INTO europe (Num,playername,Friendcode,Country,Skype,Twitter,Youtube)
VALUES (3, 'kjghskj', 't4glofshgk', 'es', 'jgd', '49hfis', 'vvvv44444')"

How safe is this query method

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! :)

Categories