I would like to add comments to a database using a simple form. For whatever reason, I can't seem to get the table to update when I use said form. I'm not getting any errors, it's just that nothing happens when I refresh the table afterwards. In other words, even after submitting the form, the table still has 0 entries. Here is my code:
<?php
session_start();
$connection = mysql_connect("server", "username", "password");
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
// Selecting Database
mysql_select_db("database", $connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
mysql_close($connection); // Closing Connection
?>
Thank you for your help!
You don't ever actually execute your query:
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
$result = mysql_query($sql);
Other things:
if ($connection->connect_error) { is not valid. You can't use the old mysql API in an OOP fashion. You need to use mysqli for that.
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.
You are also wide open to SQL injections
You do no error checking. How do you expect to know if there are problems if you don't look for them?
(note: please change server, username, and password for your server information)
<?php
session_start();
$connection = mysql_connect("server","username","password");
if (!$connection) {
die('Connect Error: ' . mysql_error());
}
// Selecting Database
mysql_select_db("database",$connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name,Title,Comments)
VALUES ('$name', '$title', '$comments')";
mysql_query($sql);
mysql_close($connection); // Closing Connection
?>
For security (defense against SQL injection) you can using mysql_real_escape_string function for limit input fields. For example:
$name = mysql_real_escape_string($_POST['name']);
$title = mysql_real_escape_string($_POST['title']);
$comments = mysql_real_escape_string($_POST['comments']);
Related
Please i have a little problem here. the below code i wrote was meant to insert into two tables simultaneously but it those not work. but if i remove the second INSERT the first INSERT will work dont know whats wrong. ITs meant insert in the first table and also collect the last Insert Id of the First table to the Second table. What did i do wrong
<?php
$english_name = $_POST['EnglishName'];
$tel_number = $_POST['TelNumber'];
$email_address = $_POST['EmailAddress'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$region = $_POST['Region'];
mysql_connect("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db("fruitmarket");
$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
$query.="'".$english_name."', ";
$query.="'".$tel_number."', ";
$query.="'".$email_address."', ";
$query.="'".$gender."', ";
$query.="'".$age."', ";
$query.="'".$region."')";
$query .= "INSERT INTO data_category (id, english_name)
VALUES (LAST_INSERT_ID(), '$english_name');";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
?>
its almost 2018, so please stop using depreciated and removed mysql_* functions use PDO/mysqli with prepared statements.
I have re-written your code with prepared statements, please follow these links :
Why shouldn't I use mysql_* functions in PHP?
How can I prevent SQL injection in PHP?
Prepared statements
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "fruitmarket";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = "INSERT INTO data (english_name,tel_number,email_address,gender,age,region) VALUES(?,?,?,?,?,?)";
$sql = $conn->prepare($stmt);
$sql->bind_param("ssssis", $english_name, $tel_number, $email_address, $gender, $age, $region);
if ($sql->execute()) {
$id = $sql->insert_id;
$insert = $conn->prepare("INSERT INTO data_category (id, english_name) VALUES(?,?)");
$insert->bind_param("is", $id, $english_name);
if ($insert->execute()) {
echo "data inserted successfully";
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
Prepared statements basically work like this:
Prepare: An SQL statement template is created and sent to the
database. Certain values are left unspecified, called parameters
(labeled "?"). Example: INSERT INTO myTabvle VALUES(?, ?, ?)
The database parses, compiles, and performs query optimization on
the SQL statement template, and stores the result without executing
it
Execute: At a later time, the application binds the values to the
parameters, and the database executes the statement. The application
may execute the statement as many times as it wants with different
values Compared to executing SQL statements directly, prepared
statements have three main advantages:
Prepared statements reduces parsing time as the preparation on the
query is done only once (although the statement is executed multiple
times)
Bound parameters minimize bandwidth to the server as you need send
only the parameters each time, and not the whole query
Prepared statements are very useful against SQL injections, because
parameter values, which are transmitted later using a different
protocol, need not be correctly escaped. If the original statement
template is not derived from external input, SQL injection cannot
occur.
I tested the above code and noticed you just need just to add and change some code see my below example
<?php
$english_name = $_POST['EnglishName'];
$tel_number = $_POST['TelNumber'];
$email_address = $_POST['EmailAddress'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$region = $_POST['Region'];
mysql_connect("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db("fruitmarket");
$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
$query.="'".$english_name."', ";
$query.="'".$tel_number."', ";
$query.="'".$email_address."', ";
$query.="'".$gender."', ";
$query.="'".$age."', ";
$query.="'".$region."')";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
$query= "INSERT INTO data_category (id, english_name)
VALUES (LAST_INSERT_ID(), '$english_name');";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
?>
test it to check if it will work
I am fairly new to SQL and I am trying to write code to insert information from a messages form. Here is the SQL code:
$con = mysqli_connect($hostname,$username,$password,$db);
// Check connection
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$message = mysqli_real_escape_string($con, $_POST['message']);
$sql = "INSERT INTO messages (name, email, message) VALUES ( '$name' , '$email' , '$message' )";
if (!mysqli_query($sql)) {
die ('Error: ' . mysqli_error());
}
else {
echo "<html><script language='JavaScript'> alert('Thank you for your submission.'),window.location = 'home'</script></html>";
}
This code returns "Error: " that I interpreted as it thinking there is an error, but there isn't any errors. The connection variables in mysqli_connect are all correct, but I am unsure if I am using the mysqli_real_escape_string correctly and even the $sql statement, because this code also doesn't insert anything into my database. Thanks in advance.
As per the mysqli_query() documentation, if you are using the procedural notation you need to include your mysqli link:
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
This would suggest you need to pass in $con to mysqli_query() as you have with your other function calls as below:
mysqli_query($con, $sql)
Also, please look up and read about parametrization as your code as it is should not be used on a live site as you are vulnerable to SQL injection. Please take the time to read this and learn how to prevent it.
Try running the query this way
mysqli_query($con, $sql);
mysqli_query requires the link to your db connection which is "$con"
I'm a newbie to php and have been having issues on a project.I created a database and a table,created the register page and everything seems ok.however,all the details entered on the register page aren't appearing in the database.please can anyone help debug?the php code is as shown below
<?php
session_start();
require_once('config.php');
?>
<?php
if (isset($_POST['register'])){
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['confirm_password'];
$sql = $con->query("INSERT into 'users' (id, name, email,
password,confirm_password) VALUES ('', {$name}', '{$email}',
'{$password}', '{$cpassword}')");
die ("cannot connect to database;");
}
?>
CONFIG FILE:
<?php
$con = mysqli_connect("localhost", "root", "","knux");
?>
You are mixing procedural and object oriented approaches. mysqli_connect returns handle, not object so you cannot use $con->something. Use this to create db connection:
$con = new mysqli('localhost', 'root', '', 'knux');
More: http://php.net/manual/en/mysqli.construct.php
There is a single quote missing from your "n"
('', {$name}', '{$email}', '{$password}', '{$cpassword}')
It should be:
('', '{$name}', '{$email}', '{$password}', '{$cpassword}')
There might be issues from your html however, you can try these:
Make sure your fields are coming from the HTML from, you can do this with
print_r($_POST);
If you see all the input, then the fault is not from the HTML.
In this case, there's really no need for you to have two PHP tags in one file, instead of
<?php
session_start();
require_once('config.php');
?>
<?php
if (isset($_POST['register'])){
$name = $_POST['name'];
...
?>
You can have:
<?php
session_start();
require_once('config.php');
if (isset($_POST['register'])){
$name = $_POST['name'];
...
?>
Use backticks when referring to the database elements like the table, instead of:
INSERT into 'users' (id, name, email, password,confirm_password)
do:
INSERT into `user` (`id`, `name`, `email`, `password`,`confirm_password`)
Use mysql_error(); in your or die(); so you'll have:
or die(mysql_error());
This should tell you exactly what the issue is.
Since you're still learning however, ill recommend PDO instead of PHP's mysql_ functions. If you're feeling too comfortable with it, you can use the mysqli_ functions instead. I makes all the difference ;)
There is 'n single quote missing {$name}'
Also if id is auto increment it can be removed from the INSERT statement
Correct Way:
$sql = $con->query("INSERT into `users` (name, email,
password,confirm_password) VALUES ('{$name}', '{$email}',
'{$password}', '{$cpassword}')");
I'm developing a web app for movie reviews. I am writing the page where reviews are created and am having issues with the data for a new review being uploaded to the MySQL database. When I submit a new review I get the created successfully message, however the database remains unchanged.
The POST data is gathered by forms located on the same page.
Connect.php:
<?php
$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('mydb');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
?>
Here's my PHP code:
<?php
session_start();
require("connect.php");
if(isset($_SESSION['critic_name'])){
$movie_id=NULL;
if (isset($_POST['reviewmovie']) && isset($_POST['rating'])){
$movie_title = $_POST['reviewmovie'];
$review_title = $_POST['review_title'];
$movie_id = mysql_query("SELECT movie_id FROM Movies WHERE 'movie_title'=".$_POST['reviewmovie']." ") or die(mysql_error());
$mem_id = mysql_query("SELECT mem_id FROM Members WHERE 'critic_name'=".$_SESSION['critic_name']." ") or die(mysql_error());
$rating = $_POST['rating'];
$comments = $_POST['comments'];
$result = mysql_num_rows($movie_id);
$result2 = mysql_num_rows($mem_id);
if(!$result && !$result2){
$query = mysql_query("INSERT INTO `Reviews` (review_id, rating, comments, mem_id movie_id, review_title) VALUES ('$rating', '$comments', '$mem_id', '$movie_id', '$review_title')");
if($query){
$msg = "Review Created Successfully.";
}
}
}
}
?>
Remove the quotes from both WHERE 'movie_title' and WHERE 'critic_name' those are column names and not variables. If you absolutely want to wrap them in something, use backticks `` `.
Plus, change ".$_POST['reviewmovie']." to '".$_POST['reviewmovie']."' and ".$_SESSION['critic_name']." to '".$_SESSION['critic_name']."'
You also forgot a comma in between mem_id and movie_id (which will break your query).
(review_id, rating, comments, mem_id movie_id, review_title)
^ // <- right there
Change it to:
(review_id, rating, comments, mem_id, movie_id, review_title)
Sidenote: Your present code is open to SQL injection. Use mysqli_* functions. (which I recommend you use and with prepared statements, or PDO)
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Thank you guys, worked it out, turns out it was in the js a word wasn't spelled correctly, always something simple
This is my script to write data to my database on my local server, it currently only writes to 2 fields, not the alias one, have I done anything wrong? I've triple checked the names in both the html form and the database field.
<?php
// 1. Create connection to database
mysql_connect('localhost','root','') or die('Could not connect to mysql: <hr>'.mysql_error());
// 2. Select database
mysql_select_db("trialdb") or die('Could not connect to database:<hr>'.mysql_error());
// 3. Assign variables (after connection as required by escape string)
$alias = $_POST['alias'];
$name = $_POST['name'];
$email = $_POST['email'];
// 4. Insert data into table
mysql_query("INSERT INTO user_data (alias, name, email) VALUES ('$alias', '$name', '$email')");
Echo 'Your information has been successfully added to the database.';
print_r($_POST);
mysql_close()
?>
First of all you should always check if the POST variables are being sent correctly:
if (
!isset($_POST['alias']) or
!isset($_POST['name']) or
!isset($_POST['email'])
) // something is wrong
Second, you don't want to inject user input directly into the sql query. You should perform some escaping first (or even better replace the mysql_* deprecated drivers with PDO or mysqli and just use prepared statements):
$alias = mysql_real_escape_string($_POST['alias']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
Third, you may want to check if the query performed correctly before printing a success message:
$res = mysql_query("INSERT INTO user_data (alias, name, email) VALUES ('$alias', '$name', '$email')");
echo ($res)
? 'Your information has been successfully added to the database.'
: 'Your information couldn't be added to the database';
you can try
<?php
$conn = mysql_connect('localhost','root','') or die('Could not connect to mysql: '.mysql_error());
mysql_select_db("trialdb", $conn) or die('Could not connect to database:'.mysql_error());
$alias = $_POST['alias'];
$name = $_POST['name'];
$email = $_POST['email'];
mysql_query("INSERT INTO user_data (`alias`, `name`, `email`) VALUES ('$alias', '$name', '$email')", $conn);
echo 'Your information has been successfully added to the database.';
print_r($_POST);
mysql_close();
?>