sql connecting two forms to a database - php

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.

Related

PHP code no longer works when switching to mysqli

I'm trying to convert some php code that uses mysql into mysqli code. I'm not sure why it doesn't work - I didn't write the original code and am not that comfortable with the hash part of it, and it seems to be where the issue is. As I show in the code below, the "error" part gets echo'ed so it's something to do with the hash strings, but I don't really understand why changing to mysqli has broken the code. Both versions of the code are below, and the original code works. I deleted the variables (host name, etc.) but otherwise this is the code I am working with.
Mysql Code:
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
$db_link = mysql_connect($host_name, $user_name, $password) //attempt to connect to the database
or die("Could not connect to $host_name" . mysql_connect_error());
mysql_select_db($db_name) //attempt to select the database
or die("Could not select database $db_name");
return $db_link;
}
$db_link = db_connect(""); //connect to the database using db_connect function
// Strings must be escaped to prevent SQL injection attack.
$name = mysql_real_escape_string($_GET['name'], $db_link);
$score = mysql_real_escape_string($_GET['score'], $db_link);
$hash = $_GET['hash'];
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $hash) {
// Send variables for the MySQL database class.
$query = "insert into scores values (NULL, '$name', '$score');";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
}
Mysqli code (doesn't work):
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
$db_link = mysqli_connect($host_name, $user_name, $password) //attempt to connect to the database
or die("Could not connect to $host_name" . mysqli_connect_error());
mysqli_select_db($db_link, $db_name) //attempt to select the database
or die("Could not select database $db_name");
return $db_link;
}
$db_link = db_connect(""); //connect to the database using db_connect function
// Strings must be escaped to prevent SQL injection attack.
$name = mysqli_real_escape_string($_GET['name'], $db_link);
$score = mysqli_real_escape_string($_GET['score'], $db_link);
$hash = $_GET['hash'];
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $hash) {
// Send variables for the MySQL database class.
$query = "INSERT INTO `scores` VALUES (NULL, '$name', '$score');";
$result = mysqli_query($db_link, $query) or die('Query failed: ' . mysqli_error($db_link));
echo $result;
}
else {
echo "error"; //added for testing. This part gets echoed.
}
mysqli_close($db_link); //close the database connection
One notable "gotchu" is that the argument order is not the same between mysql_real_escape_string and mysqli_real_escape_string, so you need to swap those arguments in your conversion.
$name = mysqli_real_escape_string($db_link, $_GET['name']);
$score = mysqli_real_escape_string($db_link, $_GET['score']);
It's good that you're taking the time to convert, though do convert fully to the object-oriented interface if mysqli is what you want to use:
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
// Enable exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli($host_name, $user_name, $password);
$db->select_db($db_name);
return $db;
}
$db = db_connect(""); //connect to the database using db_connect function
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $_GET['hash']) {
// Don't include ; inside queries run through PHP, that's only
// necessary when using interactive MySQL shells.
// Specify the columns you're inserting into, don't leave them ambiguous
// ALWAYS use prepared statements with placeholder values
$stmt = $db->prepare("INSERT INTO `scores` (name, score) VALUES (?, ?)");
$stmt->bind_param("ss", $_GET['name'], $_GET['score']);
$result = $stmt->execute();
echo $result;
}
else {
echo "error"; //added for testing. This part gets echoed.
}
// Should use a connection pool here
$db->close();
The key here is to use prepared statements with placeholder values and to always specify which columns you're actually inserting into. You don't want a minor schema change to completely break your code.
The first step to solving a complex problem is to eliminate all of the mess from the solution so the mistakes become more obvious.
The last if statement is controlling whether the mysql query gets run or not. Since you say this script is echoing "error" form the else portion of that statement, it looks like the hashes don't match.
The $hash variable is getting passed in on the URL string in $_GET['hash']. I suggest echo'ing $_GET['hash'] and $real_hash (after its computed by the call to MD5) and verify that they're not identical strings.
My hunch is that the $secretKey value doesn't match the key that's being used to generate the hash that's passed in in $_GET['hash']. As the comment there hints at, the $secretKey value has to match the value that's used in the Javascript, or the hashes won't match.
Also, you may find that there's a difference in Javascript's md5 implementation compared to PHP's. They may be encoding the same input but are returning slightly different hashes.
Edit: It could also be a character encoding difference between Javascript and PHP, so the input strings are seen as different (thus generating different hashes). See: identical md5 for JS and PHP and Generate the same MD5 using javascript and PHP.
You're also using the values of $name and $score after they've been escaped though mysqli_real_string_escape, so I'd suggest making sure Javascript portion is handling that escaping as well (so the input strings match) and that the msqli escape function is still behaving identically to the previous version. I'd suggest echo'ing the values of $name and $score and make sure they match what the Javascript side is using too. If you're running the newer code on a different server, you may need to set the character set to match the old server. See the "default character set" warning at http://php.net/manual/en/mysqli.real-escape-string.php.

Nothing show ups in MySQL database

I have a problem displaying my information in the database using phpmyadmin. I have 2 files (form.php and connect.php), it says it's connected to the database but nothing shows up in my database.
Is there any solution for that? I spent almost a whole day trying to resolve that.
Here's connect.php:
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password=''; **i don't have a password.
mysql_connect($mysql_host,$mysql_user,$mysql_password)
echo"connection sucess";
$link = mysqli_connect("localhost","root","") or die ("Couldn't not connect");
mysqli_select_db($link, "cooperative_db");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo "Successfully connected \n";
$FIRST_NAME = $_POST['FIRST_NAME'];
$LAST_TIME = $_POST['LAST_NAME'];
$CIVIC_NUMBER = $_POST['CIVIC_NUMBER'];
$STREET = $_POST['STREET'];
$CITY = $_POST['CITY'];
$PROVINCE = $_POST['PROVINCE'];
$POSTAL_CODE = $_POST['POSTAL_CODE'];
$COUNTRY = $_POST['COUNTRY'];
//$TELEPHONE = $_POST['TELEPHONE'] . $_POST['TELEPHONE'] . $_POST['TELEPHONE'];
$INCOME = $_POST['INCOME'];
//$INCOME_SOURCE = $_POST['element_6_1'] . $_POST['element_6_2'] . $_POST['element_6_3'] . $_POST['element_6_4'] .
//$_POST['element_6_5'];
$sql = "INSERT INTO candidat(FIRST_NAME, LAST_NAME, CIVIC_NUMBER, STREET, CITY, PROVINCE, POSTAL_CODE, COUNTRY, INCOME) VALUES ('$FIRST_NAME', '$LAST_TIME', '$CIVIC_NUMBER', '$STREET','$CITY', '$PROVINCE', '$POSTAL_CODE', '$COUNTRY', '$INCOME')";
?>
It seems like you may have many issues in your code. Let's start step by step.
I am not sure if that: "**i don't have a password." is actually inside your code, so change it first of all to //i don't have a password..
Now, in the second picture you showed us, it only echo 1 line instead of two, and inside your code you actually have two lines that should echo a result.
echo"connection sucess"; and echo "Successfully connected \n";
This could be due to the fact that you forgot a ; in the line right before the first echo.
mysql_connect($mysql_host,$mysql_user,$mysql_password);
May I ask you why are you using both mysql, and mysqli? If it's just for testing, there's no harm in it, plus you should know that mysql is deprecated and no longer supported or updated, you better just use mysqli, please refer to this post Why shouldn't I use mysql_* functions in PHP?.
The first picture shows that you don't have a table named candidat, yet in your code you have this: INSERT INTO candidat. Maybe you wanted this to be INSERT INTO cooperative_table instead?
Please make those small fixes, and tell us your result.
Edit: I forgot to mention, just like tadman commented, you better be aware of the SQL Injection bugs you have and fix them accordingly.

PHP Sql injection vulnerable [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I wrote the below script as my very first ever php mysql application. I am self taught and the code works as intended. My host thinks it may be vulnerable to sql injection attacks but cannot tell me why or what I should change to make it better. I'm sure it's not as clean as it could be but if anyone has any suggestions or insight I would certainly appreciate it.
<form method="post" action="search.php?go" id="searchform">
<?php
$db=mysql_connect ("server", "*", "*") or die ('I cannot connect to the database because: ' . mysql_error());
$mydb=mysql_select_db("*");
$category_sql="SELECT distinct category FROM Members";
$category_Options="";
$category_result=mysql_query($category_sql) or die ('Error: '.mysql_error ());
while ($row=mysql_fetch_array($category_result)) {
$category=$row["category"];
$category_Options.="<OPTION VALUE=\"$category\">".$category.'</option>';
}
?>
<p>
<SELECT NAME="category"><OPTION VALUE=0>Choose<?=$category_Options?></SELECT>
</p>
<input name="submit" "id="submit" type="submit" value="submit" />
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
$category=$_POST['category'];
$category=mysql_real_escape_string($category);
$sql="SELECT category, company, address, city, state, zip, phone, web, addescription, image
FROM Members
WHERE category LIKE '$category'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$category2=$row["category"];
$company=$row["company"];
$address=$row["address"];
$city=$row["city"];
$state=$row["state"];
$zip=$row["zip"];
$phone=$row["phone"];
$web = $row["web"];
$addescription = $row["addescription"];
$image = $row["image"];
echo "<blockquote>";
if(#file_get_contents($image))
{
echo "<img src='".$image ."' class='image'/>\n";
}
else
{
}
echo "<p>\n";
echo "</br>".$category2 . "\n";
echo "</br><b>".$company . "</b>\n";
echo "</br>".$address . "\n";
echo "</br>".$city . ", ".$state. " ".$zip . "\n";
echo "</br>".$phone . "\n";
echo "</br>".$web ."\n";
echo "</br>".$addescription . "\n";
echo "</br><a href=http://www.printfriendly.com style=color:#6D9F00;text-decoration:none; class=printfriendly onclick=window.print();return false; title=Printer Friendly and PDF><img style=border:none; src=http://cdn.printfriendly.com/pf-button.gif alt=Print Friendly and PDF/></a>\n";
echo "</p>";
echo "</blockquote>"
;
}
}
else{
echo "<p>Please select a Category</p>";
}
}
mysql_close($db)
?>
The MySQL functions are deprecated. Using the MySQLi functions, and prepared statements, are a better way to protect against sql injection attacks.
$stmt = $mysqli->prepare('SELECT category, company, address, city, state, zip, phone, web, addescription, image FROM Members WHERE category LIKE ?');
$stmt->bind_param('s', $category);
I'll show the implementation of a PDO connection and how to query with it. Here it goes!
First we create the connection variable with your database credentials. We'll store this connection in $db.
$username = "root";
$password = "";
$host = "localhost";
$dbname = "my_database";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8"; $username, $password, $options);
}catch(PDOException $ex){
die("Failed to connect: ".$ex->getMessage());
}
Now you have a PDO connection stored in $db which you can query through. You may want to account for magic quotes if you're not using PHP 5.4, so keep that in mind.
Otherwise, create your query statement like so..
$query = "SELECT category, company, address, city, state, zip, phone, web, addescription, image FROM Members WHERE category LIKE :category"
Afterwards, you want to bind the value from the $_POST['category'] variable (or $category since you created that) to the parameter :category. Do that like so:
$query_params = array( ':category' => $category);
Finally, now that you have the statement and the parameters, use the previously created $db variable to prepare and execute the statement.
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
Since we're SELECTing data where it could return multiple rows (assuming you have multiple rows within a category), we need to account for that. Grab the rows that the statement returns like so:
$rows = $statement->fetchAll();
And now you could refer to column headers within each $row of the database table by utilizing a foreach statement.
$citiesArray = array();
foreach($rows as $row){
if(isset($row['city'])){
$citiesArray[] = $row['city'];
}
}
Hope that helps out!
Just remember the golden rule of never trusting your users. Never take any raw user input and insert it into a database, as there's a chance that you have left yourself wide open for a security issue.
Your code seems fine. However, do note that MySQL is deprecated as of PHP 5.5.0, and instead you should use MySQLi or PDO extension which provide more security.
Maybe that's the reason your host said such thing, but from a quick look on your code it seemed fine to me.
Cheers.
The problem is the follwoing part in your code
$sql = "SELECT category, company, address, city, state, zip,
phone, web, addescription, image
FROM Members
WHERE category LIKE '$category'";
$result=mysql_query($sql);
If the parameter $category is read from the GET or POST parameters, it should be escaped:
$sql = "SELECT category, company, address, city, state, zip,
phone, web, addescription, image
FROM Members
WHERE category LIKE '" . mysql_real_escape_string($category) . "';";
If you are doing it this way, the variable cannot be used for SQL Injection
By the way (like Matthew Johnson said), the procedural mysql extension is deprecated since PHP 5.5. You should better use Mysqli or PDO.
The OOP way (strongly recommended) would look like:
$pdo = new PDO($dsn, $user, $password, $options);
$statement = $pdo->prepareStatement(
"SELECT category, company, address,
city, state, zip, phone, web,
addescription, image
FROM Members
WHERE category LIKE :category;");
$statement->bindParam(':category', $category, PDO::PARAM_STR);
$statement->execute();
$categories = $statement->fetchAll();

What is wrong with my MySQL query?

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.

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