Add row in MySQL database - php

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')"

Related

Inputting an apostrophe in my search box throws up an error [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I have a perplexing issue that I can't seem to comprehend...
I have two SQL statements:
The first enters information from a form into the database.
The second takes data from the database entered above, sends an email, and then logs the details of the transaction
The problem is that it appears that a single quote is triggering a MySQL error on the second entry only! The first instance works without issue, but the second instance triggers the mysql_error().
Does the data from a form get handled differently from the data captured in a form?
Query 1 - This works without issue (and without escaping the single quote)
$result = mysql_query("INSERT INTO job_log
(order_id, supplier_id, category_id, service_id, qty_ordered, customer_id, user_id, salesperson_ref, booking_ref, booking_name, address, suburb, postcode, state_id, region_id, email, phone, phone2, mobile, delivery_date, stock_taken, special_instructions, cost_price, cost_price_gst, sell_price, sell_price_gst, ext_sell_price, retail_customer, created, modified, log_status_id)
VALUES
('$order_id', '$supplier_id', '$category_id', '{$value['id']}', '{$value['qty']}', '$customer_id', '$user_id', '$salesperson_ref', '$booking_ref', '$booking_name', '$address', '$suburb', '$postcode', '$state_id', '$region_id', '$email', '$phone', '$phone2', '$mobile', STR_TO_DATE('$delivery_date', '%d/%m/%Y'), '$stock_taken', '$special_instructions', '$cost_price', '$cost_price_gst', '$sell_price', '$sell_price_gst', '$ext_sell_price', '$retail_customer', '".date('Y-m-d H:i:s', time())."', '".date('Y-m-d H:i:s', time())."', '1')");
Query 2 - This fails when entering a name with a single quote (for example, O'Brien)
$query = mysql_query("INSERT INTO message_log
(order_id, timestamp, message_type, email_from, supplier_id, primary_contact, secondary_contact, subject, message_content, status)
VALUES
('$order_id', '".date('Y-m-d H:i:s', time())."', '$email', '$from', '$row->supplier_id', '$row->primary_email' ,'$row->secondary_email', '$subject', '$message_content', '1')");
You should be escaping each of these strings (in both snippets) with mysql_real_escape_string().
http://us3.php.net/mysql-real-escape-string
The reason your two queries are behaving differently is likely because you have magic_quotes_gpc turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Brien" -> "O\'Brien").
Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Brien". So, you will need to pass it through mysql_real_escape_string().
For anyone finding this solution in 2015 and moving forward...
The mysql_real_escape_string() function is deprecated as of PHP 5.5.0.
See: php.net
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_real_escape_string()
PDO::quote()
You should do something like this to help you debug
$sql = "insert into blah values ('$myVar')";
echo $sql;
You will probably find that the single quote is escaped with a backslash in the working query. This might have been done automatically by PHP via the magic_quotes_gpc setting, or maybe you did it yourself in some other part of the code (addslashes and stripslashes might be functions to look for).
See Magic Quotes
You have a couple of things fighting in your strings.
lack of correct MySQL quoting (mysql_real_escape_string())
potential automatic 'magic quote' -- check your gpc_magic_quotes setting
embedded string variables, which means you have to know how PHP correctly finds variables
It's also possible that the single-quoted value is not present in the parameters to the first query. Your example is a proper name, after all, and only the second query seems to be dealing with names.
You can do the following which escapes both PHP and MySQL.
<?
$text = '';
?>
This will reflect MySQL as
How does it work?
We know that both PHP and MySQL apostrophes can be escaped with backslash and then apostrophe.
\'
Because we are using PHP to insert into MySQL, we need PHP to still write the backslash to MySQL so it too can escape it.
So we use the PHP escape character of backslash-backslash together with backslash-apostrophe to achieve this.
\\\'
You should just pass the variable (or data) inside "mysql_real_escape_string(trim($val))"
where $val is the data which is troubling you.
I had the same problem and I solved it like this:
$text = str_replace("'", "\'", $YourContent);
There is probably a better way to do this, but it worked for me and it should work for you too.
mysql_real_escape_string() or str_replace() function will help you to solve your problem.
http://phptutorial.co.in/php-echo-print/

Can't Get Simple SQL Insert to Work

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

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' )' at line 1

$q = "INSERT INTO subjects (menu_name, position, visible) VALUES ('{$mname}', {$pos}, {$vis}) ";
if(mysql_query($q)) {
header("Location: content.php");
}
else {
echo mysql_error();
}
Here, $mname is a string. $pos and $vis are integers.
Where is the mistake?
try to use only single quote to query variable rather pseudo(i think pseudo variable needs to be also quoted for query) like
$q= "INSERT INTO subjects (menu_name, position, visible) VALUES ('$mname', '$pos', '$vis')";
If you're going to use braces to try and prevent the greedy nature of variable expansion, you should use them properly.
The string "{$pos}", when $pos is 42, will give you "{42}", which is clearly not a valid integer in terms of your SQL statement. What you're looking for is instead:
${pos}
In this case, of course, you don't actually need the braces since the characters following the variable name cannot be part of a variable name - they are, respectively, ', , and ).
You only need to use braces when the following character could be part of a variable name. For example, consider:
$var = "pax";
$vara = "diablo";
In that case, $vara will give you diablo while ${var}a will give you paxa.
And I give you the same advice I seem to give weekly here :-) If you have a query that's not working, print it out! You'll find that the problem will usually become immediately obvious once you see the query in the final form you're passing to the DBMS.
And, as per best practices, I'll advise against using this method of creating queries. Anyone that's investigated SQL injection attacks (google for sql injection or, my favourite, little bobby tables) soon learns that they should use parameterised queries to prevent such attacks.
you are missing ' sign as the error says.
$q = "INSERT INTO subjects (menu_name, position, visible) VALUES ('$mname', '$pos', '$vis') ";
The value will be stored to table. Just make datatype to int in mysql table if you want it to be integer and make validation not to enter string while inserting.
You cannot name a column name whenever you run something through MySQL. One way to check is to run the query within HeidiSQL. MySQL functions will be highlighted blue, so you know if the column name becomes blue to not use it. Also; Here's a quick run of PDO to make things a little bit better; I'd suggest looking further into it as well.
public function MakeMenu() {
$q = <<<SQL
INSERT INTO subjects (menu_name,_position,visible)
VALUES(":menu_name","_position","visible")
SQL;
$resource = $this->db->prepare( $query );
$resource->execute( array (
'menu_name' => $_POST['menu_name'],
'_position' => $_POST['position'],
'visible' => $_POST['visible'],
));
}
To make things easy enough you can just make a call.php page as well. Make the calls.php page require your class page and add a hidden input to your form. IE
<input type=hidden" id="process" value="make_menu">
Then within the calls.php page add
if ( isset($_POST['process']) )
{
switch ($_POST['process'])
{
case 'make_menu':
$class->MakeMenu();
break;
I know this isn't just a quick answer, but I'm hoping you'll look further into what's happening here and move away from mysql functions. I have seen posts from people running IIS servers and not having any luck with any of the deprecated functions. Not sure how long it will be until Apache follows suite, but don't waste your time with something that's being deprecated as we speak.

Can't figure out what's wrong with my php/sql statement

So this is probably a dumb beginner question, but I've been looking at it and can't figure it out. A bit of background: just practicing making a web app, a form on page 1 takes in some values from the user, posts them to the next page which contains the code to connect to the DB and populate the relevant tables.
I establish the DB connection successfully, here's the code that contains the query:
$conn->query("SET NAMES 'utf9'");
$query_str = "INSERT INTO 'qa'.'users' ('id', 'user_name','password' ,'email' ,'dob' ,'sx') VALUES (NULL, $username, $password, $email, $dob, $sx);";
$result = #$conn->query($query_str);
Here's the error that is returned:Insert query failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''qa'.'users' ('id', 'user_name' ,'password' ,'email' ,'dob' ,'s' at line 1
Thanks in advance!
Unless it's changed since I did MySQL in PHP, escape your db/column/table names with backticks (`), not apostrophes (').
A good general trouble-shooting technique is to make the query work via another interface to the database. For example, phpMyAdmin. If it works there, you have some confidence going forward. or you may find how to fix your SQL. (phpMyAdmin is handy because it will convert your SQL into a ready-made string for PHP.)
You need to escape your column names with a backtick (`) instead of (')
You also need to properly escape the actual values you are inserting as well (use a single quote)
OMG not a single right answer
$query_str = "
INSERT INTO `qa`.`users` (`id`, `user_name`,`password` ,`email` ,`dob` ,`sx`)
VALUES (NULL, '$username', '$password', '$email', '$dob', '$sx')";
identifiers being quoted with backticks, while strings being quoted with apostrophes!
and I hope you have passed all your variables through mysql_real_escape string BEFORE putting it into query, i.e.:
$username = mysql_real_escape string($username);
and so on

mystery mysql error

I'm by no means experienced in mysql and keep getting an error in this lines of code:
$sql= "INSERT INTO songs (unique_show_id, artist, date, year, city, state, venue, taper, transfered_by, source, mic_loc, lineage, uploaded_by, uploaded_on, show_notes, show_xml)
VALUES('$showId', '$artist', '$showDate', '$year, '$city', '$state', '$venue', '$taper', '$transferer', '$source', '$mic_loc', '$lineage', '$uploader', NOW(), '$show_notes', '$show_xml')";
//check to see if the query went through
if (!mysql_query($sql,$con)){
echo "query fail";
die('Error: ' . mysql_error());
}
I'm sure it's something simplistic, but I can't see where the error is. The error message I get is:
query failError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ipuhgbi', 'CA', '', '', '', '', '', '', 'danwoods', NOW(), '', '<show id=\'gm198' at line 2
Some of the values I'm inserting are NULL, but from what I've read I don't think that should be a problem. Any ideas?
Missing quote after $year.
When MySQL issues such an error (near bla di bla), the error is usually immediately before the string it mentions. In this case 'ipuhgbi' maps to $city, so you know it's right before '$city', and what do we see there? Voila, a missing quote.
You need to use mysql_real_escape_string() in each and every single one of your $variables.
Also, read this StackOverflow question carefully regarding SQL Injections.
It looks like the last single quote on the error line is not escaped.
you need to remember to sanitize all of the strings going into the query.
There are quite few things you need to be sure about:
You don't insert primary keys through queries (eg unique_show_id in your code)
For numbers you don't use single quotes.
It is better to use the set variant of inserting records which avoids count problems eg:
Use intval for numbers and mysql_real_escaps_string for strings to avoid injections issues as well as single quotes query erros.
insert into table set field='field_value', field2='field_value' // and so on

Categories