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"
Related
I've followed a year old online tutorial of Unity Client - PHP Server - Database integration. The code seems to execute fine, it reaches the 'echo"Success"' line etc perfectly.
However when I look at my database, there is nothing there. Its blank, and I have no idea why.
Note: The online tutorial used mysql... whereas I'm using the (non-depracted) mysqli... but there didn't seem to be that much of a difference, but I'm a total rookie at PHP coding, only having minimal experience at it so it is very possible I'm wrong?
<?php
/**
* Created by PhpStorm.
* User: Josh
* Date: 09/04/2016
* Time: 14:11
*/
$Username = $_REQUEST["Username"];
$Password = $_REQUEST["Password"];
$Hostname = "localhost";
$DBName = "statemilitaryrpdb";
$User = "root";
$PasswordP = "";
$link = mysqli_connect($Hostname, $User, $PasswordP, $DBName) or die ("Can't Connect to DB");
if (!$Username || !$Password) {
echo "Empty";
} else
{
$SQL = "SELECT * FROM accounts WHERE Username = '" . $Username ."'";
$Result = #mysqli_query($link, $SQL) or die ("DB ERROR");
$Total = mysqli_num_rows($Result);
if($Total == 0)
{
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
$SQL1 = mysqli_query($link, $insert);
$Result2 = #mysqli_query($link, $SQL) or die ("DB ERROR");
echo(mysqli_num_rows($Result2));
}
else
{
echo"Username Already Used";
}
}
mysqli_close($link);
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
Answer: Username and Password are the fields but you are trying to insert Username, Password and 0
Suggestion: Do more than just MD5 encryption, that is SUPER easy to decrypt.
Edit:
Also like #andrewsi said in the comments if your only going to check if its empty, than anyone could SQL inject your database and drop your tables or make changes. Make sure that you are filtering your inputs correctly.
Firstly, your query have only 2 columns, but you are inserting 3 values:
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
Columns
Username
Password
Values to insert
$Username
md5($Password)
0
Thus, not all the values will be inserted.
Secondly, for MySQL related names, you need to use back ticks instead of single-quote.
Thus, this:
INSERT INTO 'accounts'
Should be:
INSERT INTO `accounts`
Thirdly, your code is vulnerable to MySQL Injection, you should prevent it using mysqli_real_escape_string():
$Username = mysqli_real_escape_string($link, $_REQUEST["Username"]);
$Password = mysqli_real_escape_string($link, $_REQUEST["Password"]);
Tip: You shouldn't suppress error messages:
#mysqli_query($link, $SQL)
Remove # to enable error reporting. It's very useful in diagnosing syntax errors.
Also, you shouldn't use md5() to hash passwords, as it's not very secure. Use password_hash and password_verify instead.
In debug mode, never use # to suppress errors, ie. #mysqli_query. Also or die("DB ERROR") isn't very descriptive. Even if that resolves, what good does DB ERROR provide you? Instead, use or die( mysqli_error($link) ) to see what's really going on with the query.
You also have 3 values to be inserted, but only 2 columns represented in the query statement:
('Username', 'Password') // 2 columns
VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)"; // 3 values
What column is 0 being inserted into? This value needs to be represented by a column.
And a table/column name should never be wrapped with quotes; only ticks `accounts`
so i have this php code :
session_start();
$servername = "localhost";
$username = "root";
$dbname = "3890ask3_db";
$con = mysql_connect($servername, $username, "", $dbname)
or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db($dbname,$con)
or die("Failed to connect to MySQL: " . mysql_error());
$query = mysql_query("SELECT * FROM register where Username = '$_SESSION[Username]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(isset($_GET['selecttoy']))
{
$clname=$row['Name'];
$clsurname=$row['Surname'];
$clemail=$row['Email'];
$stoy=$_GET['selecttoy'];
$query2 = "INSERT INTO order (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('$clname', '$clsurname', '$clemail' , '$stoy', ' ' )" ;
if (mysql_query($query2)) {
echo "Order created successfully!";
} else {
echo "Error: " . "<br>" . mysql_error($con);
}
}
?>
The php page can actually read the get variable,but as soon as i try to insert something in the database, i get this error message:
"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 'order (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('mar', 'kyr', 'dgg' at line 1"
i tried everything but no result...can someone please help me?
thanks in advance....
You can not use order directly because it's reserved word. try to enclose it in (``). Like below:-
$query2 = "INSERT INTO `order` (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('$clname', '$clsurname', '$clemail' , '$stoy', ' ' )" ;
Note:- Try to add sql error reporting code always.
stop using mysql_*, use mysqli_* or PDO.
your above code is open for SQL Injection. thanks.
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']);
I have a database running on my server with phpmyadmin but I can't connect with it. Here is an example:
$user_name = "xxxxx";
$password = "xxxxx";
$database = "xxxxx";
$host = "db.xxxx.nl";
$db_handle = mysql_connect($host, $user_name, $password);
$db_found = mysql_select_db($database);
But this doesn't seem to work. If I try to insert some values into a table it still stays empty.
$sql = "INSERT INTO tbl_forum
(
title,
name,
content,
lastname,
post_image
)
VALUES
(
'{$_POST['contactsubject']}',
'{$_POST['contactname']}',
'{$_POST['contactmessage']}',
'{$_POST['contactlastname']}',
'{$_FILES["contactBrowse"]["name"]}'
)";
Am I doing something wrong?
I'm going to completely rewrite your code. As you are clearly new to databases within PHP, there is absolutely no reason not to use the new mysqli API.
Your connection should look something like this;
$mysqli = new mysqli($host,$user_name,$password,$database);
if ($mysqli->connect_errno) echo "Failed to connect to MySQL: " . $mysqli->connect_error;
This will create a new database object called $mysqli (or you can call it what you like, such as $db).
You can then prepare your SQL statement and execute it. In the code below, we have 5 parameters that are represented in the SQL as ?, and then we bind the variables to those 5 parameters. The first argument in bind_param tells the API the 5 parameters are 5 strings (hence s x5). For integers, use i;
if($query = $mysqli->prepare("INSERT INTO tbl_forum (title,name,content,lastname,post_image) VALUES (?,?,?,?,?)")) {
$query->bind_param('sssss',$_POST['contactsubject'],$_POST['contactname'],$_POST['contactmessage'],$_POST['contactlastname'],$_FILES["contactBrowse"]["name"]);
$query->execute();
}
else {
echo "Could not prepare SQL: " . $mysqli->error;
}
Assuming all your connection information is correct, this will insert your information into the database as required.
Hope this helps.
I think the last value '{$_FILES["contactBrowse"]["name"]}' has some problem. Try this and get the sql after preparing(echo $sql;) to debug by your self.
$file_name = $_FILES["contactBrowse"]["name"];
$sql = "INSERT INTO tbl_forum
(
title,
name,
content,
lastname,
post_image
)
VALUES
(
'{$_POST['contactsubject']}',
'{$_POST['contactname']}',
'{$_POST['contactmessage']}',
'{$_POST['contactlastname']}',
'{$file_name}'
)";
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();
?>