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());
}
Related
We have an assignment for school and I've tried to build the application, however some text that I want to have inserted into a database doesn't get submitted.
I've tried different things, but the page does not show an error either.
This is the code of my insert page
<head>
</head>
<body>
<form action="index.php" method="post">
ID: <input type="text" name="id"><br/>
Server: <input type="text" name="Server"><br/>
Student: <input type="text" name="Student"><br/>
Docent: <input type="text" name="Docent"><br/>
Project: <input type="text" name="Project"><br/>
Startdatum: <input type="text" name="Startdatum"><br/>
Einddatum: <input type="text" name="Einddatum"><br/>
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])) {
$con = mysqli_connect("localhost", "root", "usbw", "serverruimte");
if(!$con) {
die(mysqli_connect_error());
}
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
$result = mysqli_query($con, $sql);
if($result) {
echo "Opslaan voltooid!";
} else {
echo mysqli_error($con);
}
mysqli_close($con);
}
?>
</body>
</html>
Basically, what happens is: https://i.imgur.com/aUOx5yj.mp4
Does anyone know what the problem is and why the inserted data does not show up on the index page? The data does show on the page when I submit it directly into the MYSQL database.
Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough!
When working with MySQLi you should enable automatic error reporting instead of checking for errors manually. Checking for errors manually is a terrible practice, very error prone and should be avoided at all costs. Let MySQLi throw exceptions and do not catch them. See How to get the error message in MySQLi?
When opening MySQLi connection you must specify the correct charset. The recommended one is utf8mb4.
if (isset($_POST['submit'])) {
// Enable automatic error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Create new instance of MySQLi class
$con = new mysqli("localhost", "root", "usbw", "serverruimte");
// Set correct charset. Important!
$con->set_charset('utf8mb4');
$stmt = $con->prepare('INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES (?,?,?,?,?,?,?)');
$stmt->bind_param('sssssss', $_POST['id'], $_POST['Server'], $_POST['Student'], $_POST['Docent'], $_POST['Project'], $_POST['startdatum'], $_POST['einddatum']);
$stmt->execute();
echo "Opslaan voltooid!";
mysqli_close($con);
}
Change this line:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
to:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('".$_POST['id']."','".$_POST['Server']."','".$_POST[Student]."','".$_POST['Docent']."','".$_POST['Project']."','".$_POST['Startdatum']."','".$_POST['Einddatum']."')";
Reason behind this change is because your query is wrong for the following reasons:
You were using strings instead of concatenating your real values coming from $_POST
Some of your indexes in $_POST were misspelled. For example:
$_POST[einddatum] should be $_POST['Einddatum']
Also, consider that this code is vulnerable to SQL Injection
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);
}
?>
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 :).
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.
I would like a user to be able to insert a "bid" into a MySQL table using a php form - this is only for demo, not live purpose. I get the following error message,
Error: 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 ''90','2011-07-13'' at line 3 (Line 3 refers to my tag?) I figure it doesnt like the form inputs just being "text" type, but no idea how to fix it - all advice very welcome, this is my form & php code below;
<form action="insert.php" method="post">
<div><label for="commodity">Commodity</label><input type="text" name="commodity"/></div>
<div><label for="region">Region</label><input type="text" name="region"/></div>
<div><label for="member">Member</label><input type="text" name="member" /></div>
<div><label for="size">Size</label><input type="int" name="size" /></div>
<div><label for="price">Post Bid</label><input type="decimal" name="price" /></div>
<div><label for="posted">Date Posted</label><input type="text" name="posted"/></div>
<P><label for="submit">Submit Bid</label><input type="submit" /></P>
</form>
& php
<?php
$con = mysql_connect("localhost","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("palegall_newTrader", $con);
$sql="INSERT INTO `buy` (commodity, region, member, size, price, posted)
VALUES
('$_POST[commodity]','$_POST[region]','$_POST[member]','$_POST[size]','$_POST[price]','$_POST[posted]'";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Many thanks in advance, scotia
You're vulnerable to SQL injection, and your POST probably contains a ', which is causing the syntax error. Try the following:
$commodity = mysql_real_escape_string($_POST['commodity']);
$region = mysql_real_escape_string($_POST['region']);
etc...
$sql = "INSERT INTO ... VALUES ('$commodity', '$region', etc...)";
the escape function will ensure that any SQL metacharacters in the data are escaped, so they can't "break" your query. Never EVER directly insert user-provided data into an SQL query, even if it's a simple script that only you will ever use. Get into the habit of escaping everything (or better yet, using PDO prepared statements), because at some point, you'll get burned if you don't.
Your closing parenthesis need to go after the last value to be inserted, now it's after the 4th element. Put it at the and of the statement.
$sql="INSERT INTO `buy` (commodity, region, member, size, price, posted)
VALUES
('$_POST[commodity]','$_POST[region]','$_POST[member]','$_POST[size]','$_POST[price]','$_POST[posted]')"
Also, follow #Marc's advice and sanatize your input.
Shouldn't it be
$sql="INSERT INTO `buy` (commodity, region, member, size, price, posted) VALUES ('$_POST[commodity]','$_POST[region]','$_POST[member]','$_POST[size]','$_POST[price]','$_POST[posted]')";
There is a misplaced parenthesis after $_POST['size'] that should be after $_POST[posted]
The SQL should look like this:
$sql="INSERT INTO `buy` (commodity, region, member, size, price, posted)
VALUES
('$_POST[commodity]','$_POST[region]','$_POST[member]','$_POST[size]','$_POST[price]','$_POST[posted]')";