What is wrong with my MySQL query? - php

So, I have a form that posts to my php file using ajax, and succeeds. But the following query doesn't insert anything. Can someone help me understand what I'm doing wrong?
My php file:
<?php
include 'connect.php' ;
$type = mysql_real_escape_string($_POST['type']);
$title = mysql_real_escape_string($_POST['title']);
$content = mysql_real_escape_string($_POST['content']);
if ($type == 'Just Text') {
mysql_query("INSERT INTO articles (title, type, thisisaninteger, content) VALUES ('".$title."', '".$type."', 0, '".$content."')")or die("MySQL Error: " . mysql_error());
}
?>
My connect.php:
<?php
$dbhost = "localhost";
$dbname = "example";
$dbuser = "test";
$dbpass = "test";
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>

If you aren't receiving any errors and the INSERT just doesn't happen, it is most likely because the if statement fails to be true. Verify that $type actually matches Just Text.
You should also be inserting values using prepared statements, and use PDO or MySQLi - this article will help you decide which.

first, echo "something" after the if statement and recall the data with your ajax post. you can find out if your if statement is working, then try formatting your variables like so
mysql_query("INSERT INTO articles (title, type, thisisaninteger, content) VALUES ('$title', '$type', 0, '$content')")or die("MySQL Error: " . mysql_error());

I just want to throw in an official vote/recommendation in favor of switching to a parameterized SQL statement, too. In spite of the use of mysql_real_escape_string, schlepping a SQL statement together via string concatenation is neither necessary nor a good idea. Honestly, I find a prepared statement much, much easier to read than the typical string-concatenation exercise, as well:
$stmt = $dbh->prepare("SELECT * FROM users WHERE USERNAME = ? AND PASSWORD = ?");
$stmt->execute(array($username, $password));

Alright, it was a stupid mistake on my side. There were columns I didn't include and they were not being assigned a value. Thanks everyone for helping out.

Related

sql connecting two forms to a database

I'm a beginner when it comes to the topic. I've followed this tutorial to connect one form to a database and it worked well. Now I'd like to add another form and my questions are:
do I create separate function in connection.php?
do I create a separate table in the same database?
how do I generate a separate thank you message?
The other form is a contact form.
connection.php:
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "responses";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
thankyou.php
<?php
require 'connection.php';
$conn = Connect();
$email = $conn->real_escape_string($_POST['u_email']);
$query = "INSERT into newsletter (email) VALUES('" . $email . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo $_GET["form"];
echo "Thank you for subscribing to our newsletter. <br>";
$conn->close();
?>
The second form would look like this:
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$message = $conn->real_escape_string($_POST['message']);
$query = "INSERT into contactForm (name,email,message) VALUES('" . $name . "','" . $email . "','" . $message . "')";
$success = $conn->query($query);
I've created two tables: newsletter and contactForm. Now, how do I direct form input to the right table?
1 - You can "require"/"include" the same connection.php wherever it suit you / need it
2 - you can create on the same Database a new table and do action on this new on your query example:
$query = "INSERT into newsletter (email) VALUES('" . $email . "')";
$success = $conn->query($query);
$query = "INSERT into newsletter_schedule (email,schedule_date) VALUES('" . $email . "', NOW())";
$success = $conn->query($query);
or you can create in a different db and change db name connected(more complex but sometimes needed)
3 - you can do in separate static file and redirect to using (PHP function)
header("location: tankyou.html");//put your file name/must be the first output, even a space before can throw a error
leave more details about the 3rd if is not what you are looking for
Unfortunately, your question, "How do I...?" is a bit broad in this case. Any number of ways. The only real way to get a sense for these things is to try a number of times. You may fail, but that's where the most learning happenings.
Your specific questions:
do I create separate function in connection.php?
Depends on what you need. I might include a 'CloseConnection' or 'TearDown' function, but doing so is not strictly necessary in PHP. (PHP does it's best to close down and stop using any resources you still have open at the end of your script.)
However, if you want to edge toward better practices, get in the habit now of always cleaning up after yourself. What you learned in kindergarten applies: if you opened it, close it. If you created it, dispose of it. If you allocated it, deallocate it. etc.
do I create a separate table in the same database?
Yes. This question is related to schema design, and again, you will just have to try things out and see what works for your situation and thought processes. You will know that things are not right when the logic gets really convoluted. But knowing that comes with nothing other than experience.
how do I generate a separate thank you message?
The same way you generate any other HTML. Some version of echo, print, or include/require. Given your current setup, I might create a separate function for this logic.
One thing which is not what you asked for, but which I feel compelled to point out: heavily consider prepared statements for your SQL, rather than string interpolation. That is ...
BAD:
$query = "INSERT into newsletter (email) VALUES('" . $email . "')";
$success = $conn->query($query);
BETTER/GOOD:
$sql = "INSERT INTO newsletter (email) VALUE ( ? )";
$statement = $conn->prepare( $sql );
$statement->bind_param('s', $email);
$statement->execute();
This is perhaps slightly more complicated, but also precludes any need for sanitization like real_escape_string.
For more information, read the documentation and google prepared statements, but the gist is this: for security reasons now, and higher performance later. By telling the database what will be coming, you preclude someone from injecting something you didn't expect or want.

Unable to INSERT data into MySQL through HTML form using PHP [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
Here is my Form:
<html>
<head>
<title>Stats</title>
</head>
<body>
<h2>Member Information Form</h2>
<form action="submit_mbr_nfo.php" method="post">
Member ID <input type ="text" name= "mbrid"/><br>
Member Name <input type="text" name="mbrnm"/><br>
Actual Name <input type="text" name="atlnm"/><br>
<input type="submit" value="Save"/>
</form>
</body>
</html>
Here is my PHP file:
<?php
//Define database properties in global variables
define('DB_NAME', 'STATS');
define('DB_USER', 'root');
define('DB_PASSWORD', 'Test');
define('DB_HOST', 'localhost');
//store connection props in var
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
//check connection
if (!$link) {
die ('Could not connect to the Database: ' . mysql_error());
}
//map $_POST to vars
$mbr_id = mysql_real_escape_string($link, $_POST['mbrid']);
$mbr_nm = mysql_real_escape_string($link, $_POST['mbrnm']);
$atl_nm = mysql_real_escape_string($link, $_POST['atlnm']);
$sql = 'INSERT INTO MBR_NFO '.'(MBR_ID,MBR_NM,ATL_NM) '.'VALUES ('$mbr_id', '$mbr_nm','$atl_nm')';
mysql_select_db('STATS');
$exe_query = mysql_query( $sql, $link);
?>
And here is my php error log:
PHP Parse error: syntax error, unexpected '$mbr_id' (T_VARIABLE) in /Applications/MAMP/htdocs/stats/submit_mbr_nfo.php on line 21
I am very new and learning PHP and HTML, i tried several online solutions but nothing has worked so far. I am able to insert into DB if I don't use $_POST, i.e., manually typing in the values in php code, but that's not the goal, the goal is to use Form to populate MySQL DB. Any help is appreciated, thank you.
Try following query
$sql = "INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES ('$mbr_id', '$mbr_nm','$atl_nm')";
You are having issues with string concatenation and quotes. Try following query:
$sql = "INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES('$mbr_id', '$mbr_nm','$atl_nm')";
if you set primary key and auto increment on database for member id
so it very easy.you are not write mbr_id in query
$query="INSERT INTO MBR_NFO (MBR_NM,ATL_NM) VALUES( '$mbr_nm','$atl_nm')";
it's simple way
if you want not set primary key and autoincrement and try this code
$query ="INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM). VALUES('$mbr_id', '$mbr_nm','$atl_nm')";
You should use prepared statements (see below) instead of manually concateting the query string. But, since you’re new to PHP, let us first fix your code. The line
$sql = 'INSERT INTO MBR_NFO '.'(MBR_ID,MBR_NM,ATL_NM) '.'VALUES ('$mbr_id', '$mbr_nm','$atl_nm')';
has a couple of flaws. In PHP, string concatenation is done via the dot . operator, which you have used only partly. In order to construct the query string $sql, you have to add a couple of dots:
$sql = 'INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES (' . $mbr_id . ', ' . $mbr_nm . ',' . $atl_nm . ')';
While this is valid PHP syntax, it is still no valid SQL. If your user input is $mbr_id = 42, $mbr_nm = 'amit', $atl_nm = 'Amit Kumar', then after concatenation, $sql looks like
INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES (1, amit, Amit Kumar)
and is missing quotes around the strings amit and Amit Kumar. At best, this makes your query invalid; at worst, it makes your query prone to injection attacks. Therefore, build your query using
$sql = 'INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES ("' . $mbr_id . '", "' . $mbr_nm . '","' . $atl_nm . '")';
or, because in PHP, variables in strings that are quoted with double quotes – e.g. "my name is $name", but not 'my name is $name' – are evaluated:
$sql = "INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES ('$mbr_id', '$mbr_nm,'$atl_nm')";
By far the best practise, however, is using prepared statements and parameterized queries:
$con = new PDO('mysql:host=localhost;dbname=STATS', 'root', 'Test');
$stmt = $con->prepare('INSERT INTO MBR_NFO (MBR_ID,MBR_NM,ATL_NM) VALUES (:mbr_id, :mbr_nm, :atl_nm)');
$stmt->bindValue(':id', $mbr_id);
$stmt->bindValue(':mbr_nm', $mbr_nm);
$stmt->bindValue(':atl_nm', $atl_nm);
$stmt->execute();

MySQL error code 0 in PHP? Cannot insert data into database with PHP [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
So trying to insert some data from a PHP page into my SQL database. This page is ONLY accessible via myself so I'm not worried about it being accessed or SQL injectable etc. My issue is no matter what code I use it doesn't go into the database. I've tried coding it myself, using template codes, taking from php.net etc nothing has worked!
It now redirects me with the success message but still nothing in the database.
Code will be put below and I'll edit some of my details for privacy reasons.
<?php
require connect.php
// If the values are posted, insert them into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$isadminB = $_POST['isadmin'];
$password = $_POST['password'];
$query = "INSERT INTO `users` (user_name, password, isadmin) VALUES ('$username', '$password', '$isadminB')";
$result = mysql_query($query);
if($result){
$msg = "User Created Successfully.";
}
}
$link = mysql_connect("localhost", "root", "password");
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
The echo mysql_errno($link) . ": " . mysql_error($link). "\n"; was the code that gave me error code 0?
As requested the code for the form from my previous page.
<form action="account_create_submit.php" method="post">
Username: <input type="text" name="username" id="username"> <br /><br />
Password: <input type="password" name="password" id="password"> <br /><br />
<span id="isadmin">Is Admin: Yes<input type="radio" name="isadmin" id="1" value="1"> | No<input type="radio" name="isadmin" id="0" value="0"><br /></span>
<span id="submit"><input type="submit" value="Create Account"></span>
</form>
Ok so changed the form code so method is now POST. Great! All data is being read correctly although that wasn't my issue as even typing in hard data for the code to submit wasn't working at least its a future issue resolved already. The new error code is no longer 0 but rather the following:
1064: 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 ''user_name', 'password', 'isadmin') VALUES ('testZ', 'lol', '1')' at line 1
Connect.php
<?php
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('Default_DB');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
Firstly, for those of you getting the misconception about password for a column name:
Sure, it's MySQL "keyword", but not a "reserved" word; more specifically, it is a function (see ref). Notice there is no (R) next to the "function (keyword) name": https://dev.mysql.com/doc/refman/5.5/en/keywords.html therefore it's perfectly valid as a column name.
Ref: https://dev.mysql.com/doc/refman/5.1/en/encryption-functions.html#function_password
Ticks are only required if it is used in order to prevent it from being recognized as a "function", which it clearly is not in the OP's case. So, get your information and facts straight.
More specifically, if a table named as PASSWORD and without spaces between the table name and the column declaration:
I.e.: INSERT INTO PASSWORD(col_a, col_b, col_c) VALUES ('var_a', 'var_b', 'var_c')
which would throw a syntax error, since the table name is considered as being a function.
Therefore, the proper syntax would need to read as
INSERT INTO `PASSWORD` (col_a, col_b, col_c) VALUES ('var_a', 'var_b', 'var_c')
(Edit:) To answer the present question; you're using $connection in your connection, but querying with $link along with the missing db variables passed to your query and the quotes/semi-colon I've already outlined here.
That's if you want to get that code of yours going, but I highly discourage it. You're using a deprecated MySQL library and MD5 as you stated. All old technology that is no longer safe to be used, nor will it be supported in future PHP releases.
You're missing a semi-colon here require connect.php and quotes.
That should read as require "connect.php";
You should also remove this:
$link = mysql_connect("localhost", "root", "password");
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
you're already trying to include a connection file.
Use this in your connection file: (modified, using connection variable connection parameter)
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('Default_DB', $connection);
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
and pass the $connection to your query as the 2nd parameter.
$result = mysql_query($query, $connection);
Add error reporting to the top of your file(s) right after your opening PHP tag
for example <?php error_reporting(E_ALL); ini_set('display_errors', 1); then the rest of your code, to see if it yields anything.
Also add or die(mysql_error()) to mysql_query().
If that still gives you a hard time, you will need to escape your data.
I.e.:
$username = mysql_real_escape_string($_POST['username'], $connection);
and do the same for the others.
Use a safer method: (originally posted answer)
May as well just do a total rewrite and using mysqli_ with prepared statements.
Fill in the credentials for your own.
Sidenote: You may have to replace the last s for an i for the $isadminB that's IF that column is an int.
$link = new mysqli('localhost', 'root', 'password', 'demo');
if ($link->connect_errno) {
throw new Exception($link->connect_error, $link->connect_errno);
}
if (!empty($_POST['username']) && !empty($_POST['password'])){
$username = $_POST['username'];
$isadminB = $_POST['isadmin'];
$password = $_POST['password'];
// now prepare an INSERT statement
if (!$stmt = $link->prepare('INSERT INTO `users`
(`user_name`, `password`, `isadmin`)
VALUES (?, ?, ?)')) {
throw new Exception($link->error, $link->errno);
}
// bind parameters
$stmt->bind_param('sss', $username, $password, $isadminB);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
}
else{
echo "Nothing is set, or something is empty.";
}
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
You can also use this PDO example pulled from one of ircmaxell's answers:
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above)
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
You are using "get" as your form submission method. "post" variables won't be recognized.
Also...
It looks like you're missing the second parameter of your mysql_query() function which is your link identifier to the MySQL connection. I'm assuming you've created the connection in connection.php.
Typically, the mysql_query() function would be
$result = mysql_query($query, $conn);
with $conn having been pre-defined in your connection.php file.
password is a special word in MySQL, and it might be necessary to put the word in quotes like `password`.
Why are you putting all the information from the form in the link on submit? ex: account_create_submit.php?username=myusername&password=mypassword&isadmin=0
I can see that $username = $_POST['username']; doesn't match the username in your query string.
$query = "INSERT INTOusers(user_name, password, isadmin) VALUES ('$username', '$password', '$isadminB')";
While your fixing that why don't you just make $isadminB and $_POST['isadmin'] the same. Use 'isadminB' in both places.
Check that out and see what happens!

What is wrong with my PHP/SQL registration script?

I'm trying to make my first registration script using PHP/SQL. Part of my code isn't working:
if(!$errors){
$query = "INSERT INTO users (email, password) VALUES ($registerEmail, $registerPassword)";
if(mysqli_query($dbSelected, $query)){
$success['register'] = 'Successfully registered.';
}else{
$errors['register'] = 'Registration did not succeed.';
}
}
When I test my code I get the error 'Registration did not succeed.' For reference, $errors and $success are arrays. Is there anything wrong with this part of my script?
$dbSelected is:
$dbLink = mysqli_connect('localhost', 'root', 'PASSWORD');
if (!$dbLink) {
die('Can\'t connect to the database: ' . \mysqli_error());
}
$dbSelected = mysqli_select_db($dbLink, 'devDatabase');
if (!$dbSelected) {
die('Connected database, but cannot select
devDatabase: ' . \mysqli_error());
}
I'm sure I am connecting and selecting the database.
Any help would be greatly appreciated! I am very new to PHP/SQL so forgive me for any noob mistakes.
Quote the string like below
$query = "INSERT INTO users (email, password) VALUES ('$registerEmail', '$registerPassword')";
You can also do
echo $query;
and take the output on the browser, copy and paste into PHPMyAdmin and execute it from there. It should tell you what is wrong with the query.
I suggest you to use prepared statement as using string concatenation in SQL Statement is prone to SQL injection attack. Refer the example PHP mysqli prepare
First off, PHP is deprecating mysql_ functions, you should migrate to PDO instead.
Also, make sure since you're using the older mysql_ functions to sanitize your entries using mysql_real_escape_string
Also, your entries need to be quoted. Here's a redo of your query string:
$query = "INSERT INTO users (email, password) VALUES ('{$registerEmail}', '{$registerPassword}')";

I cant get the form data to go into database. What am I doing wrong?

CODE UPDATED, STILL NOT WORKING.
I know I´m apparently using mysql function which will be outdated. But for now all I want is for this code to work. I want to know what I´m doing wrong:(
I´m very new to php and databases... I have been struggling to get simple html form data to go into the database table. And I just can´t get it to work:( Can anyone help and see what is wrong with my code? I´ve just done a simple table in the database with the fields ID, FIRSTNAME and SURNAME.
Here is the code:
<?php
//connect to database
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';
$mysql_db = 'test';
if (!mysql_connect ($mysql_host, $mysql_user, $mysql_pass)||!mysql_select_db ($mysql_db) ) {
die(mysql_error());
}
// Code
if (isset($_POST['firstname'])&&
isset($_POST['surname'])) {
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
if (!empty($username)&&!empty($password)) {
$query = "INSERT INTO `test`.`test_tabell`
VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
/*$query = "INSERT INTO `test`.`test_tabell` VALUES (``, `.$firstname.`, `.$surname.`)"; */
$query_run = mysql_query($query);
if (!$query_run) echo mysql_error();
}
}
?>
<form action="add.php" method="POST">
Firstname:<br> <input type="text" name="firstname" value="<?php if (isset($firstname)) { echo $firstname; } ?>"><br><br>
Surname:<br> <input type="text" name="surname" value="<?php if (isset($surname)) { echo $surname; } ?>"><br><br>
<input type="submit" value="Submit">
</form>
Thank you!
Don't use mysql specific syntax, It's outdated and it begins to be annoying when you need to do some high level stuff, and you can't switch to sqlite or postgresql.
I recommend using PDO, you can do something like:
// Usage: $db = connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables (I think you forgot to define the name of the database);
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$GLOBALS['db'] = connectToDataBase($host , $databaseName, $user, $pass);
Now you have an instance of a PDO database donnection.
One thing I want to point out is that you're vonurable to sql injections, you want to use prepared statements in your query, like:
$query = "INSERT INTO test(first_name, sur_name) VALUES (:firstname, :surname);";
Where we will execute two variables $firstName and $surName on the query, making them replace the values of :firstName and :surName, let me show you by first creating a simple insertion function:
function insertFunction($db, $query, $firstName, $surName)
{
$statement = $db->prepare($query);
return $statement->execute(array(":firstName" => $firstName, ":surName" => $surName));
}
So It's easy for you to do something like
$firstName = 'Smith';
$surName = 'John';
$db = $GLOBALS['db'];
$success = insertFunction($db, $query, $firstName, $surName);
Now you can check if it was successful or not, by checking whether $success is true or false.
If you want to see more advanced use of PDO (multiple rows etc) then you can check out one of my comments here: Javascript function as php?
(Not the top comment).
I hope this helps. Please comment if anything is odd.
Hard to tell without seeing your schema but try this:
$query = "INSERT INTO `test`.`test_tabell` VALUES ('', '$firstname', '$surname')";
$query_run = mysql_query($query);
You're using backticks instead of apostrophes. Also, you're trying to execute a query before defining what the query is.
Your insert query is wrong and also open to SQL injections. Here's how it should be:
$query = "INSERT INTO `test`.`test_tabell`
VALUES ('', '" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
Notice the changing of all backticks to apostrophe.
Also, you're trying to execute the query before defining it.
EDIT
As per your information related to table definition, you can skip the id field from your table. The INSERT query will become:
$query = "INSERT INTO `test`.`test_tabell` (`FIRSTNAME`, `SURNAME`)
VALUES ('" . mysql_real_escape_string($firstname) . "', '" . mysql_real_escape_string($surname) . "')";
$query_run = mysql_query( $query );
As posted in the comments, you REALLY SHOULD NOT use/learn/practice using any function that starts with "mysql_" since it will NOT work as soon as PHP is updated. These functions are on their way out. Best of luck with learning to use PHP and SQL databases - just make sure you're learning something that will be useful in the future. Make sure to read up on Object Oriented Programming (OOP) in relation to PHP and both the PDO and mysqli_* functions.

Categories