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`
Related
Below is the code I have in my Sublime, but the database isn't being called.
<?php$username="root";
$password="changedpassword";$database="User";
$field1-name=$_POST['name'];
$field2-name=$_POST['password'];
$field3-name=$_POST['email'];
$field4-name=$_POST['sex'];
$field5-name=$_POST['school'];
$field6-name=$_POST['birth'];
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO create_user (name, password, email, sex, school, birth) VALUES('','$field1-name','$field2-name',
'$field3-name','$field4-name','$field5-name','$field6-name')";mysql_query($query);mysql_close();?>
Let's go through this step by step. First, here's your current code, tidied up to be readable:
<?php
$username = "root";
$password = "changedpassword";
$database = "User";
$field1_name = $_POST['name'];
$field2_name = $_POST['password'];
$field3_name = $_POST['email'];
$field4_name = $_POST['sex'];
$field5_name = $_POST['school'];
$field6_name = $_POST['birth'];
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die("Unable to select database");
$query = "
INSERT INTO
create_user
(
name,
password,
email,
sex,
school,
birth
)
VALUES
(
'',
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
";
mysql_query($query);
mysql_close();
?>
I've made only two changes (tidied the whitespace, and used _name instead of -name, as PHP variables cannot contain hyphens), but it's already a big improvement. The code is no longer an eyesore. It does not have syntax errors, and it is readable. There are still, though, a large number of problems.
First, you see that we are inserting seven values into six columns. This will be a problem. Fix that by removing the first blank value:
$query = "
INSERT INTO
create_user
(
name,
password,
email,
sex,
school,
birth
)
VALUES
(
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
";
Now we have something that might actually work. It's painfully insecure, with massive potential for SQL injection attacks, and it won't work on the latest PHP because the mysql_ functions have been removed, but it might actually kind of work somewhere. You wouldn't want to put it into production, but for test purposes, we're getting somewhere.
MySQL is deprecated since PHP 5.6 and is insecure, use PDO or MySQLi instead.
Connecting with MySQLi
<?php
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
$field1_name = $_POST['name'];
$field2_name = $_POST['password'];
$field3_name = $_POST['email'];
$field4_name = $_POST['sex'];
$field5_name = $_POST['school'];
$field6_name = $_POST['birth'];
$query = mysqli_query($connection, "INSERT INTO create_user
(name, password, email, sex, school, birth ) VALUES
(
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
");
Use this and you will be good. I hope this has helped you!
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 am getting the error on line 26 as shown by my browser.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "tut";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Database connection failed: ".mysqli_connect_error());
}
if (isset($_POST['register']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$pass2=$_POST['password1'];
if(empty($username)||empty ($password)||empty($password1)){
echo "Oops! Can't leave any field blank";
}
elseif($pass!=$pass2){
echo "Passwords don't match";
}
else{
$phash = sha1(sha1($pass."salt")."salt");
$sql=IF NOT EXISTS (SELECT * FROM users WHERE username = '$user')
INSERT INTO users (id, username, password) VALUES ('', '$user', '$phash')
ELSE
RAISERROR 'Username exists, please select a different one';
$result = mysqli_query($conn, $sql);
}
}
?>
Is this not a correct way of writing the IF NOT EXISTS statement. Also when I try to execute this directly in XAMPP I get Unrecognised SQL statement error!
This is how to do it, I have test it and it works:
$sql = "
INSERT INTO users (username, password)
SELECT * FROM (SELECT '$user', '$phash') AS tmp
WHERE NOT EXISTS (
SELECT username FROM users WHERE username = '$user'
) LIMIT 1;
";
This solution is inspired from this answer.
The problem is that you can not combine PHP and MySQL statement like you did, you need to encapsulate all MySQL statements in quote ".
What comes RAISERROR, it is not MySQL function, it belongs to Microsoft.
You could easily make php if statement that checks if $sql contain valid username and return your message. That part is left to your fantasy.
XAMPP has no thing to do with the error, it just a software that provides an Apache and MySQL installation for Windows.
Note: P.S. please learn to use parameterized queries, because your
code is vulnerable to SQL injection. thanks to #BillKarwin for mentioning this.
So im trying to get my data from my form submission to be put into a mysql database but whenever i submit a form it gives me this error: Error: INSERT INTO form_submissions(ID, first, last, phone, class) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5])
Now here is my PHP code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form_database";
$value = $_POST['first'];
$value1 = $_POST['last'];
$value2 = $_POST['phone'];
$value3 = $_POST['class'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `form_submissions`(`ID`, `first`, `last`, `phone`,
`class`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5])";
if ($conn->query($sql) === TRUE) {
echo "Submitted Successfully";
} else {``
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
assuming that ID is auto-incrementing, and that the others are text,
$sql = "INSERT INTO `form_submissions`(`first`, `last`, `phone`,
`class`) VALUES ('$value','$value1','$value2','$value3')";
Your query should be like:
INSERT INTO `form_submissions`(`first`, `last`, `phone`, `class`)
VALUES ('John','doe', '98564', 'SOMECLASS');
To check: echo the $sql query and debug it in phpmyadmin.
Note: If you enabled AUTO_INCREMENT, you can ignore the data feed of that column. It will do its job automatic.
Security tip - >
To prevent SQLi Injection check out this post.
There are two things wrong.
The first thing is you give 5 fields (ID, First, last, phone, class)
And you only have 4 variables in your post. I think you don’t need to send the ID on an insert if the column is set to auto increment in the database, So don’t send an value for the ID field.
Your variables are not correctly inserted in the query.
The [value-1] douse not mean the $value1 variable will automatically be injected in there.
This can be done in a lot of way’s
I wil give you a simple solution, (but it wil be a bad one for real websites). The simple solution is:
$sql = "INSERT INTO `form_submissions`(`first`, `last`, `phone`,`class`) VALUES (`$value`,`$value1`,`$value2`, `$value3`)";
The reason this is bad is: You are directly entering post data inside your query and are now vounerable to SQL-Injections. You need to escape your post data befoure inserting it in a query. Or better yet don’t use ‘mysqli’ but an PDO.
An good PDO example can be found here
https://www.w3schools.com/php/php_mysql_insert.asp
I hope this helps.
Your SQL is apparently wrong. It should look's like with something like that:
$sql = "INSERT INTO `form_submissions`(`ID`, `first`, `last`, `phone`,
`class`) VALUES ($value1,$value2,$value3,$value4,$value5)";
The field ID should be auto_increment. If it is, you don't need to pass value to it.
I'm kinda new to PHP and only using it for the backend of my Android App.
I've got three strings that I'm sending to the PHP from my Android App. I want to query a table called 'users' and find the userid of the username that was sent from my Android App and then inset the data into a seperate table called 'msg'.
I've tried for my life and I cannot get it to work, plus I haven't even finished.
thanks and helping me would be pretty amazing, as I'm new to PHP and can't finish off the rest of the code.
PHP:
<?php
$username = $_POST['username'];
$msg = $_POST['msg'];
$frienduser = $_POST ['frienduser'];
/*mysql data below */
$dbc = mysql_connect('localhost', 'removemypasswords', 'again');
if(!dbc) {
die("Something went wrong! Try again...");
}
/* select database */
$db_select = mysql_select_db("andagain, $dbc");
if (!db_select){
die("Can't connect :" .mysql_error);
}
$query = mysql_query("SELECT FROM users WHERE usernames ='$usernames'");
$query1 = mysql_query(INSERT INTO `gtanews1_zips54`.`msg` (
`id` ,
`friendid` ,
`msg`
)
VALUES (
'$query', '$frienduser', 'msg'
);
echo ($msg);
?>
how about putting quotes around $query1 like
$query1 = mysql_query("INSERT INTO gtanews1_zips54.msg (`id` ,`friendid` ,`msg`)
VALUES ('$query', '$frienduser', 'msg')");
Should be
$query = mysql_query("SELECT * FROM users WHERE usernames ='$username'");
$result = mysql_fetch_array($query);
$query1 = mysql_query("INSERT INTO gtanews1_zips54.msg (id,friendid,msg) VALUES ('" . $result['yourField'] . "', '$frienduser','$msg')");
your mysql select db code is wrong. you need to have the quotes before the comma
mysql_select_db("andagain", $dbc);
also place quotes at the end of your query
$query = mysql_query("SELECT FROM users WHERE usernames ='$usernames'"); $query1 = mysql_query(INSERT INTO `gtanews1_zips54`.`msg` ( `id` , `friendid` , `msg` ) VALUES ( '$query', '$frienduser', 'msg' )");
There's a lot going wrong here:
<?php
$username = $_POST['username'];
$msg = $_POST['msg'];
$frienduser = $_POST ['frienduser'];
/*mysql data below */
$dbc = mysql_connect('localhost', 'removemypasswords', 'again');
if(!$dbc) { //- You forgot the dollar $ sign on $dbc
die("Something went wrong! Try again...");
}
/* select database */
$db_select = mysql_select_db("andagain", $dbc); //- You had the entire thing quoted, quotes are just around "andagain"
if (!db_select){
die("Can't connect :" .mysql_error()); //- You forgot the parentheses after mysql_error
}
$query = mysql_query("SELECT FROM users WHERE usernames ='$usernames'");
//- You need to actually get the results out of the query object
$row = mysql_fetch_assoc($query);
if (!$row) {
die('User not found');
}
$user_id = $row['id']; //- Or whatever the column is called
$query1 = mysql_query("INSERT INTO `gtanews1_zips54`.`msg` (
`id` ,
`friendid` ,
`msg`
)
VALUES (
'$user_id', '$frienduser', 'msg'
"); //- You forgot to put quotes around this query
echo ($msg);
?>
And that's just to start, there may be other problems depending on your database schema / data transfer format.
Also, you're wide open to SQL injection.
your code have many errors .
$db_select = mysql_select_db (andagain, $dbc);
$query = mysql_query('SELECT FROM users WHERE usernames ="$usernames"');
since Stackoverflow is not a community for fixing codes bugs ..so i am leaving this job for you .
below are some points which can help you to fix all errors ?
Variable-substitution cann't be dont with single quotes (') . double quotes allow variable substitution .
to escape quotes inside quotes , we use \
parameter cannot be encapsulated with double quotes .