I believe that something in my code is stopping the PHP being inserted into the database which is strange because I use the same setup in other forms on the site which all parse successfully.
The thing which puzzles me the most is the fact that the form will go through successfully if only a username and password are specified, but when I try to add email (also a varchar) and a group (a 1 character integer), the form fails. I’ve added my code below so hopefully you would be able to help me find out what I'm doing wrong.
PHP:
// Connecting, selecting database
$link = mysql_connect('DOMAIN', 'USERNAME', 'PASSWORD');
if (!$link)
{ die('Could not connect: ' . mysql_error());
}
mysql_select_db('DATABASE') or die('Could not select database');
// Convert form values to variables
$name = $_POST['name'];
$pass = md5($_POST['pass']);
$iemail = $_POST['email'];
$email = addslashes($iemail);
$group = $_POST['group'];
$order = "INSERT INTO `users` (name,pass,email,group)
VALUES ('$name','$pass', '$email', '$group')";
$result = mysql_query($result);
if($result)
{
echo
header("Location: manageusers.php?result=success&name=$name");
die();
}
else
{
mysql_error();
}
mysql_close($link);
HTML:
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Add User</h3>
</div>
<div class="panel-body">
<form role="form" action="adduser.php" method="post">
<div class="form-group">
<label for="name">Username</label>
<input type="name" name="name" class="form-control" id="name" placeholder="e.g: John Smith" required>
</div>
<div class="form-group">
<label for="pass">Password</label>
<input type="password" name="pass" class="form-control" id="pass" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" class="form-control" id="email">
</div>'; ?>
<div class="form-group">
<label for="group">Group</label>
<select class="form-control" name="group" id="group" required>
<option value="1">Student</option>
<option value="2">Teacher</option>
<option value="0">Admin</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
group is a reserved keyword and you should avoid these words as the column names.
However if you want to use it wrap them in backticks
`group`
Checkout the complete list here http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html
Most of the words in the table are forbidden by standard SQL as column
or table names (for example, GROUP). A few are reserved because MySQL
needs them and uses a yacc parser
The biggest error in your code is the actual mysql_query line:
$result = mysql_query($result);
So the query being run is $result (which is not even set) and the $result is the $result of the query $result? Shouldn’t that use $order instead like this:
$result = mysql_query($order);
And there are a few other issues with your code—including the use of a reserved MySQL name; group—so I have refactored your code to cover all bases. Including reworking your mysql_* calls to use mysqli_* instead since mysql_* is depreciated in PHP versions 5.3 to 5.4 and completely removed from PHP 5.5. Here it is. Notes below:
// Connecting, selecting database
$link = mysqli_connect('DOMAIN', 'USERNAME', 'PASSWORD', 'DATABASE') or die(mysqli_connect_errno());
// Set a '$_POST' array and roll through each value.
$post_array = array('name', 'pass', 'email', 'group');
foreach ($post_array as $post_key => $post_value) {
$$post_value = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// MD5 the password.
$pass = md5($pass);
// Unsure if you need to add slashes if you are using mysqli_stmt_bind_param.
// So including here if you need it. Just change the mysqli_stmt_bind_param to use $email_md5
$email_md5 = addslashes($email);
// Set the query.
$order = "INSERT INTO `users` (`name`, `pass`, `email`, `group`)"
. " VALUES (?, ?, ?, ?)"
;
// Bind the params.
mysqli_stmt_bind_param($order, 'ssss', $name, $pass, $email, $group);
// Run the query.
$result = mysqli_query($link, $order) or die(mysqli_error());
if ($result) {
header("Location: manageusers.php?result=success&name=$name");
}
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($link);
Here is the breakdown of what I did:
Your query line is this: $result = mysql_query($result); but shouldn’t that be $result = mysqli_query($order);? I rewrote that line for mysqli_* but that is the biggest error I found.
I switched your code to use MySQLi extensions which is the preferred way of doing things now since mysql_* is depreciated in PHP versions 5.3 to 5.4 and completely removed from PHP 5.5.
I also set a $_POST array so all of the post keys can be rolled through simply & have some basic validation using isset and !empty. Combing this with mysqli_stmt_bind_param gives you a lot more basic validation than your previous script had.
You are attempting to insert into a table name group but GROUP is actually a MySQL reserved word that should not be used. And if it is used, it should be placed in back ticks like shown in my code.
I am also using the command mysqli_stmt_bind_param to actually bind the parameter to the query which is a simple way to prevent agains MySQL injections. Also using mysqli_free_result and mysqli_close to neatly close the MySQL process.
Your code for the “success” makes no sense. You have an echo with nothing following it on one line, followed by header(…); call then followed by die();. I removed the echo as well as the die() since that is not technically wrong, but that is not really needed.
Related
I'm trying to insert some data to my database, but it will only insert
an unique id and userid. Rest of the attributes wont follow. Any suggestions?
Image of insert:
<?php
if(isset($_POST['project']))
{
// Escape user inputs for security
$stripped = mysql_real_escape_string($_GET['id']);
$title = mysqli_real_escape_string($_POST['title']);
$about = mysqli_real_escape_string($_POST['about']);
$code = mysqli_real_escape_string($_POST['code']);
mysql_query("INSERT INTO cms_prosjekt (userid, title, about, code) VALUES
('".$_SESSION['user']['id']."', '".$title."', '".$about."', '".$code."')") or die(mysql_error());
}
?>
HTML
<form action="" method="post">
<input type="text" class="form-control" type="text" name="title" id="title" placeholder="Fullt navn" style="margin-bottom:10px">
<input type="text" class="form-control" type="text" name="about" id="about" placeholder="Kode bedrift" style="margin-bottom:10px">
<input type="text" class="form-control" type="text" name="code" id="code" placeholder="Passord" style="margin-bottom:10px">
<button type="submit" name="project" class="button" class="btn btn-success" style="margin-bottom:10px;">Register prosjekt nå</button>
</form>
you need to provide the $link argument which is your connection to properly escape your values.
mysqli_real_escape_string ( mysqli $link , string $escapestr )
Seeing your code and that it only enters one value, this tells me you are using the mysql_ API to connect with, and you're mixing those with mysqli_real_escape_string(), and requires a db connection for it and as the first argument.
Since $stripped = mysql_real_escape_string($_GET['id']); is all that is getting entered in db, after seeing your screenshot.
Those different APIs do not intermix. You need to use the same one from connecting to querying.
In your case, that would be mysql_* - mysql_real_escape_string().
I suggest you start using a prepared statement right away.
https://en.wikipedia.org/wiki/Prepared_statement
Note: Using mysql_real_escape_string() doesn't fully protect against an SQL injection. Read the following Q&A on the subject;
SQL injection that gets around mysql_real_escape_string()
Footnotes:
The MySQL_ API has been removed as of PHP 7.0. Should your server eventually get upgraded to it, you will no longer be able to use your present code.
It's time to switch over to either using the MySQLi_ or PDO API and with a prepared statement.
References:
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/book.pdo.php
http://php.net/manual/en/pdo.prepared-statements.php
You should also check for any empty fields. Just an isset() against your submit button isn't enough.
If your site is live or will be live soon, someone may enter empty values and could trigger errors or insert empty values in your database, which I'm sure you're not going to appreciate.
Reference:
http://php.net/manual/en/function.empty.php
You have used both mysqli and mysql it should be anyone of them.
if (isset($_POST['project'])) {
$stripped = mysql_real_escape_string($_GET['id']);
$title = mysql_real_escape_string($_POST['title']);
$about = mysql_real_escape_string($_POST['about']);
$code = mysql_real_escape_string($_POST['code']);
mysql_query("INSERT INTO cms_prosjekt (userid, title, about, code) VALUES ('" . $_SESSION['user']['id'] . "', '" . $title . "', '" . $about . "', '" . $code . "')") or die(mysql_error());
}
i had write a html file which will request some information from user and send it to another php file. The php file will establish the connection to database and insert the value to database. My database name = testdbtable name = table1 I had do some testing on both file by calling an alert message, the alert messages was able to display in the html file,it's seen like the request from the html file cant send to the php file,so the code for inserting data to database can't execute
My Html form as show below
<form id="firstPrize" method="POST" action="firstPrize.php">
<label> Number 1</label>
<input type="text" name="num1"><br>
<label> Number 2</label>
<input type="text" name="num2"><br>
<label> Number 3</label>
<input type="text" name="num3"><br>
<label> Number 4</label>
<input type="text" name="num4"><br><br><Br>
<input type="button" value="enter" name="btnSubmit" onclick="show()">
</form>
firstPrize.php sample code
<?php
$host = "localhost";
$user = "root";
$password = "";
mysql_connect($host,$user,$password);
mysql_select_db("testdb") or die(mysql_error());
Session_Start();
echo("yeah");
if(isset($_POST["btnSubmit"]))
{
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$num3 = $_POST["num3"];
$num4 = $_POST["num4"];
mysql_query("insert into table1(num1,num2,num3,num4) values ('num1','num2','num3','num4')");
?>
First, your query can produce SQL Injection. Use Mysqli Prepared Statement :
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST["btnSubmit"]))
{
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$num3 = $_POST["num3"];
$num4 = $_POST["num4"];
// prepare and bind
$query = $conn->prepare("INSERT INTO table1 (num1, num2, num3, num4) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $num1, $num2, $num3, $num4);
}
This function binds the parameters to the SQL query and tells the database what the parameters are. The "ssss" argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.
The argument may be one of four types:
i - integer
d - double
s - string
Second, your if statement misses a closing bracket }
Third, your variable $num1 is never used. You use num1, num2, but you miss the '$'
First, your if statement is missing a closing }.
Second, your SQL query is not inserting the variables you've set above. You've got variables like $num1, but then you are inserting the value just 'num' in your SQL insert. You have to change 'num1', 'num2'... to '$num1', '$num2'...
Third, please do some research on PHP Data Objects (PDO) or MYSQLi (reference links at bottom of post). mysql_ is deprecated and completely vulnerable to malicious injection.
Edit: In addition, please see fred -ii-'s comments below for some sound advice on better INSERT queries. It's safe practice to verify that the values are of the type you're expecting prior to running them against your database.
fred -ii- says:
What if one of those values happens to contain an injection such as '123?
[Use]... (int)$_POST["num1"] and check to see firsthand if the input entered is an integer. There are a few functions that will do that.
Use error reporting and error checking against your query during testing and assuming that you are able to use the MySQL_ API.
References:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/function.mysql-error.php
Otherwise, you will need to resort to either using the MySQLi_ or PDO API.
References:
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php
.Change your query to;
mysql_query("insert into table1(`num1`,`num2`,`num3`,`num4`) values ('".$num1."','".$num2."','".$num3."','".$num4."')");
followed by the closing bracket ( } ) for your if statement.
<?php
session_start();
// always start your session before any other code
$host = "localhost";
$user = "root";
$password = "";
mysql_connect($host,$user,$password);
mysql_select_db("testdb") or die(mysql_error());
if(isset($_POST["btnSubmit"]))
{
$num1 = mysql_real_escape_string($_POST["num1"]);
$num2 = mysql_real_escape_string($_POST["num2"]);
$num3 = mysql_real_escape_string($_POST["num3"]);
$num4 = mysql_real_escape_string($_POST["num4"]);
// mysql isn't the safest way to put your code out, however if you do, escape it. You may be better off by using prepared statements, but thats up to you, i am just fixing this code
mysql_query("insert into table1(num1,num2,num3,num4)
values ('$num1','$num2','$num3','$num4')");
}
?>
I made a few tweaks in your code and this should do it. Note my additional comments in the code, including the propper escaping your variables, because of the injection danger. Its not my place to judge you on your code, but you would be better off by using prepared statements.
This is a very good topic on this here on stack, I suggest you read it: How can I prevent SQL injection in PHP?
As you clearly mentioned in your question,
" I had do some testing on both file by calling an alert message, the
alert messages was able to display in the html file, it's seen like the
request from the html file cant send to the php file ,so the code for inserting data to database can't execute ~#Heart Break KID "
For That,
1) Change
<input type="button" value="enter" name="btnSubmit" onclick="show()">
To
<input type="submit" value="enter" name="btnSubmit" onclick="show()">
here, type='submit' is required to submit form data..
2) Closing curly brackets are not available. Close if condition.
if(isset($_POST["btnSubmit"]))
{
// Your query.
}
Now, data will go to next page. But, read this question How can I prevent SQL-injection in PHP?
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
UPDATED CODE (using mysqli)
Html form
<form id="firstPrize" method="POST" action="firstPrize.php">
<label> Number 1</label>
<input type="text" name="num1"><br>
<label> Number 2</label>
<input type="text" name="num2"><br>
<label> Number 3</label>
<input type="text" name="num3"><br>
<label> Number 4</label>
<input type="text" name="num4"><br><br><Br>
<input type="submit" value="enter" name="btnSubmit" onclick="show()">
</form>
firstPrize.php
<?php
$host = "localhost";
$user = "root";
$password = "";
$connect = mysqli_connect($host, $user, $password, "testdb");
session_start();
if(isset($_POST["btnSubmit"]))
{
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$num3 = $_POST["num3"];
$num4 = $_POST["num4"];
$stmt = mysqli_prepare($connect, "INSERT INTO table1(num1,num2,num3,num4) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'ssss', $num1, $num2, $num3, $num4);
$query123 = mysqli_stmt_execute($stmt);
}
?>
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
Hey there i have searched but can not find the answer i am looking for. My form will not post to my database i started getting sql injected so i changed my code around to use $mysqli->real_escape_string but it does not seem to want to still post all i am getting is the error in the code any help would be greatly appreciated.
<form action="" method="post">
<br/>
<input type="text" name="Key" class="dap_text_box" placeholder="Enter Key"/><br/>
<br/>
<input type="text" name="Name" class="dap_text_box" placeholder="Name"/><br/>
<br/>
<input type="text" name="Email" class="dap_text_box" placeholder="Email"/><br/>
<br/>
<input type="text" name="IP_s_" class="dap_text_box" placeholder="Enter IP"/><br/>
<br/>
<input type="submit" name="submit" value="Key Activation" class="sendbutton"/> </form> <hr/> </body> </html>
<?php
if (isset($_POST['submit'])) {
$mysqli = new mysqli("localhost", "root", "rkPJNwe0cI", "key");
// Check
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Set charset for correct escaping
$mysqli->set_charset('utf8');
echo $_SERVER["REMOTE_ADDR"]; // mmm?
$key = $mysqli->real_escape_string($_POST['Key']);
$IP = $mysqli->real_escape_string($_POST['IP']);
$name = $mysqli->real_escape_string($_POST['Name']);
$email = $mysqli->real_escape_string($_POST['Email']);
$IP_s = $mysqli->real_escape_string($_POST["IP_s_"]);
// (ID, Key, Activated, IP, Banned)
$sql = "INSERT INTO keys (ID, Key, Activated, IP, Banned, Name, Email) VALUES ('$ID1', '$key', 1, '$IP', 0, '$name', '$email')";
$sql1 = "SELECT ID, Key, Activated, IP, Name, Email FROM Keys";
$sql = "UPDATE Keys set IP='$IP_s_', Name='$name', Email='$email', Activated='1' WHERE Key='$key'";
if ($mysqli->multi_query($sql) === TRUE) {
echo "Activated";
} else {
echo "Error";
}
$mysqli->close(); }
You have quite a few things wrong from what I can see. Too long for a comment.
You use multi_query() but only have one query defined in $sql. Your insert statement and select statement don't appear to be doing anything, you overwrite the insert statement before you call multi_query().
$ID1 doesn't appear to be defined anywhere for your insert statement.
Why not use prepared statements? So much easier and efficient than trying to escape each individual string.
first of all i am pretty new with mysql and php and for now i just want to insert some data in a mysql database form two text box using php.
here the database name is "info" and table name is "students" having three columns like id(primary key, auto increment activated), name and dept. There are two text boxes txtName and txtDept. I want that when i press the enter button the data form the text boxes will be inserted into the mysql database. I have tried the following code but data is not being inserted in the table....
<html>
<form mehtod="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info");
if($_POST){
$name = $_POST['txtName'];
$dept = $_POST['txtDept'];
echo $name;
mysqli_query($con,"INSERT INTO students(name,dept) VALUES($name,$dept);");
}
?>
There are a few things wrong with your posted code.
mehtod="post" it should be method="post" - typo.
Plus, quote your VALUES
VALUES('$name','$dept')
DO use prepared statements, or PDO with prepared statements.
because your present code is open to SQL injection
and add error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
You should also check for DB errors.
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
as well as or die(mysqli_error($con)) to mysqli_query()
Sidenote/suggestion:
If your entire code is inside the same file (which appears to be), consider wrapping your PHP/SQL inside a conditional statement using the submit button named attribute, otherwise, you may get an Undefined index... warning.
Naming your submit button <input type="submit" name="submit" value="Enter"/>
and doing
if(isset($_POST['submit'])){ code to execute }
Just doing if($_POST){ may give unexpected results when error reporting is set.
Rewrite: with some added security using mysqli_real_escape_string() and stripslashes()
<html>
<form method="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" name="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
if(isset($_POST['submit'])){
$name = stripslashes($_POST['txtName']);
$name = mysqli_real_escape_string($con,$_POST['txtName']);
$dept = stripslashes($_POST['txtDept']);
$dept = mysqli_real_escape_string($con,$_POST['txtDept']);
echo $name;
mysqli_query($con,"INSERT INTO `students` (`name`, `dept`) VALUES ('$name','$dept')")
or die(mysqli_error($con));
}
?>
As per the manual: http://php.net/manual/en/mysqli.connect-error.php and if you wish to use the following method where a comment has been given to that effect:
<?php
$link = #mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
?>
God save us all...
Use PDO class instead :). By using PDO you can additionally make prepared statement on client side and use named parameters. More over if you ever have to change your database driver PDO support around 12 different drivers (eighteen different databases!) where MySQLi supports only one driver (MySQL). :(
In term of performance MySQLi is around 2,5% faster however this is not a big difference at all. My choice is PDO anyway :).
The problem is I simply want to insert the fullname/address. I created a users table with the following columns: id (primary), fullname (unique), address (unique).
Here's the code:
<?php $username = "root";
$password = "artislife23";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("test",$dbhandle)
or die("Could not select examples");?>
<body>
<div class="container">
<div class="content">
<h1><?php if(($selected!=null)){
echo "Database is on lock.";}
if(($dbhandle!=null)){
echo "Connected to MySQL<br>";
}?></h1>
<form method="post" action="input.php">
<tr><td>Name</td><td><input type="text" name="fullname" size="20"></td></tr>
<tr><td>Address</td><td><input type="text" name="address" size="40"></td></tr>
<tr><td></td><td align="right"><input type="submit" value="Submit"></td>
Here's input.php
<?php
$postr="INSERT INTO users
(fullname, address) VALUES('$_POST[fullname]','$_POST[address]')";
$result = mysql_query($postr);
echo "$result";?>
All that I can see that's happening is a single blank entry was inserted into the table. Am I doing something wrong here? All I want is to successfully insert the form data into my users table here.
$_POST['fullname']
you are missing quotes in your POSTs.
The reason why it doesn't work is that PHP doesn't expand arrays in strings the same way it does variables without some weird syntax I can never remember. Change:
$postr="INSERT INTO users (fullname, address) VALUES('$_POST[fullname]','$_POST[address]')";
To:
$postr="INSERT INTO users (fullname, address) VALUES('".$_POST['fullname']."','".$_POST['address']."')";
You were also missing the quotes on the array keys.
Additional notes:
Your code is wide open to SQL injection, if I entered my name as Bobby'; DROP TABLE users;-- guess what would happen?
mysql_*() functions are deprecated, take the time to learn PDO or MySQLi. They have neat thigns called 'parameterized queries' that allow you to easily avoid SQL injection like I've noted above.
Assuming that either a person's full name or address to be unique to them is a design mistake, don't do this in a 'real-world' project.
Edit
Alternate syntax for embedding arrays in strings:
$string = "Fee fie {$foo['bar']}.";