I have a MySQL database named "culvers" with a user_id INT(4) auto incrementing, a full_name varchar(20) and a user_name varchar(20). I am trying to use this HTML form to add values to the table, but it is not working. I have explored dozens of tutorials and help sites, and it still isn't working. I even put the code on another hosting provider to see if that was the problem. When I click "add" I am taken to a blank page (which is expected, since I don't have a success/error message) but the form data does not insert into the database table.
Also, I know I should sanitize my inputs, but that's not the issue right now. (At least I don't think so)
Here's the form.html code:
<html>
<head>
<title>Add User to Table</title>
</head>
<body>
<h1>Add User</h1>
<form action="adduser.php" method="POST">
<label>Full name:</label>
<input id="postname" type="text" name="fullname">
<label>Username:</label>
<input id="postuser" type="text" name="username">
<input type="submit" name="submit" value="Add">
</form>
</body>
</html>
And here's the adduser.php code:
<?php
if(isset($_POST['submit'])){
$connection = mysql_connect("localhost", "xxxx", "xxxxxxxxxx");
mysql_select_db("culvers");
$fullnameOfUser = $_POST['fullname'];
$usernameOfUser = $_POST['username'];
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser');
$result = mysql_query($sql, $connection);
mysql_close($connection);
}else{
echo "Error no form data";
}
?>
Thank you very much for your help!
you have error in this line :
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser');
you did not have ending "
this line should be :
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
You should use mysqli_* or PDO since all functions of mysql_* are deprecated.
You miss the double Quotes at the end of SELECT Query
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
First if it is not a typo the you need to add a double quote to query.
$sql = "INSERT INTO users (full_name, user_name) VALUES ('$fullnameOfUser', '$usernameOfUser')";
if still issue remains then print query and run it directly in phpmyadmin to see there is not issue with query.
Note: you are using mysql_* function. Please used PDO or Mysqli as your current code is prone to Sql Injection.
PDO Link: http://php.net/manual/en/book.pdo.php
Before submitting your form data, you need to start the mysql server.
you can start mysql server by the use of xampp software. once you have started your mysql server through xampp software, you can find the mysql server port number also.
the actual format of including the database is,
mysql_connect("localhost:port/database","username","password");
You forgot to close the double quotes !
'$fullnameOfUser', '$usernameOfUser')";
----^ // Add one there
The right code.
$sql = "INSERT INTO `users` (`full_name`, `user_name`) VALUES ('$fullnameOfUser', '$usernameOfUser')";
You need to switch to PreparedStatements seriously as the above code of yours is directly prone to SQL Injection.
Related
could you please tell me why my SQL-Injection isn't working and how can I fix it. I tried to go after the example from Here, but value'); DROP TABLE table;-- or password 1=1 doesn' work. Im sorry to steal your time with these easy things, but I tried it many times and I didn't get it running and the other post didn't help me.
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: #cc0000;}
</style>
</head>
<body>
<h2>Einlogen</h2>
<form action="EasyExploit.php" method="post">
Vorname: <input type="text" name="vorname"><br>
<input type="submit">
<h2>Registrieren</h2>
<form action="EasyExploit.php" method="post">
Vorname: <input type="text" name="vorname"><br>
<input type="submit">
<?php
$connection = mysqli_connect('localhost', 'root','' ,'DB') or die(mysqli_error());
mysqli_select_db($connection ,'DB')or die(mysqli_error());
#$unsafe_variable = $_POST['vorname'];
mysqli_query($connection, "INSERT INTO `Persons` (`Vorname`) VALUES ('$unsafe_variable')");
?>
</body>
</html>
Thank's in Advance
Making sql injection vulnerable code (for testing purposes):
In order to test SQL Injection with your code we need to make some few changes:
<?php
$connection = mysqli_connect('localhost', 'root','' ,'DB') or
die(mysqli_error($connection)); //1
mysqli_select_db($connection ,'DB') or die(mysqli_error($connection)); //2
$unsafe_variable = $_POST['vorname'];
mysqli_multi_query($connection, //3
"INSERT INTO `Persons` (`Vorname`) VALUES ('$unsafe_variable')");
?>
//1 and //2: mysqli_error needs $connection parameter.
//3: Only mysqli_multi_query is able to execute more than one sentence at a time. For security reasons. mysqli_query just executes one to prevent sql injection.
Testing:
It's the time to test sql injection. We create a simple table t to check if we can drop it through sql injection:
create table t ( i int );
Time to attack, the killer string to inject sql is:
pepe'); DROP TABLE t;--
SQL with injected code:
"INSERT INTO Persons (Vorname) VALUES ('pepe'); DROP TABLE t;--')"
Explained:
SQL pattern is: "INSERT INTO Persons (Vorname) VALUES ('$unsafe_variable')"
"pepe');" replaces $unsafe_variable : "INSERT INTO Persons (Vorname) VALUES ('pepe'); DROP TABLE t;--')"
Remember -- means "comments from here", then the last quote and parenthesis is a comment.
After post this value to form:
mysql> select * from t;
ERROR 1146 (42S02): Table 's.t' doesn't exist
How to avoid SQL Injection?
Man, this is Internet, they are a lot of papers about it. Start your searching with Parameterized Queries.
I've been trying to insert some data into my database for an events page. I have an html form and a seperate script, as seen below and the submit seems to go through for the ename id and imgsrc values but nothing past that. Anything more and I get a 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 'when, descr, positions) VALUES (test, 1 ,www.vzdc.org,2017-1-20 23:59:00' at line 1I've done some reasearch but maybe it's just a weird error on my end? I'm fairly new to mysql and I would love some help! Thanks, code below.
<!-- HTML form -->
<form id="newevent" action="insertevent.php" method="post">
<p>Event Name:</p><input name="ename" type="text" width="100">
<p>ID:</p><input name="id" type="text" size="5">
<p>Banner Link:</p><input name="imgsrc" type="text" size="50">
<p>Description</p><input name="descr" type="text" height="1000px" >
<p>Date / Time (yyyy-mm-dd HH:MM:SS):</p><input name="when" type="text">
<p>Positions (ONE per line)</p><textarea name="positions" form="newevent" rows="10" cols="50"></textarea><br>
<input value="Add Event" type="submit">
</form>
/* PHP script on insertevent.php */
<?php
$link = mysqli_connect("localhost", "root", "xxx", "xxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$ename = mysqli_real_escape_string($link, $_POST['ename']);
$id = mysqli_real_escape_string($link, $_POST['id']);
$imgsrc = mysqli_real_escape_string($link, $_POST['imgsrc']);
$when = mysqli_real_escape_string($link, $_POST['when']);
$descr = mysqli_real_escape_string($link, $_POST['descr']);
$positions = mysqli_real_escape_string($link, $_POST['positions']);
// attempt insert query execution
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Don't use back-ticks for binding variables to your query, use single ticks instead. You can use back-ticks for the table and column name:
INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`)
VALUES ('$ename', '$id', '$imgsrc', '$when', '$descr', '$positions')
WHEN is also a reserved word, so better change its name.
And since you're using mysqli_* API already, check prepared statement
You are using an SQL reserved word as a column name.
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
You really shouldn't, but if you want to get away with this, surround your table/column names with back ticks ```, like this:
$sql = "INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`) VALUES ('$ename', '$id' , '$imgsrc', '$when', '$descr', '$positions')";
I've removed the back ticks you put around your values because, well, they shouldn't be there.
Please learn and use MySQLi prepared statements. They'll help.
I am having trouble trying to get some values to insert into one of my tables.
It used to work fine but have recently changed my database and now does not insert.
I have stared at it for so long now i cannot see what is wrong, hopefully some one can see what is bound to be an obvious mistake.
The code is:
<?php
$date = $_POST['date'];
$plan = preg_replace('#[^A-za-z0-9 ?!.,]#i', '', $_POST['plan']);
if (isset($_POST['date'])) {
$sql = "SELECT * FROM maingroup WHERE groupName ='$g'";
$for_query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($for_query, MYSQLI_ASSOC)) {
$user = $row["owner"];
$sessAdd = "INSERT INTO training (user, groupName, date, sessDate, plan)
VALUES('$user','$g',now(),'$date','$plan')";
$query = mysqli_query($db_conx, $sessAdd);
$gid = mysqli_insert_id($db_conx);
}
header("location: groupPage.php?g=$g");
}
?>
<form name="addSess" id="addSess" method="post">
Date of Training: <input type="text" size="12" id="date" /></br></br>
Training:
<textarea name="plan" id="plan" rows="10" cols="80">
</textarea>
<script>
CKEDITOR.replace( 'plan' );
</script>
</br></br>
<input type="submit" value="Add Training" onclick="javascript:return validateMyForm();">
</form>
I have other pages that insert fine using more or less the same code just changing the table names and columns etc. The '$g' is established at the top of the page and gets the group info.
They all include a php script that connects to the database that works fine on the other pages also and elsewhere on the same page it calls data from another table so don't think its a connection problem. I have obviously gone blind to my error so am really hoping someone can see it.
Thank you to anyone that tries.
Try below code to insert
$sessAdd = "INSERT INTO training (user, groupName, date, sessDate, plan) VALUES('$user','$g',".now().",'$date','$plan')";
Just replace
$sessAdd = "INSERT INTO training (user, groupName, date, sessDate, plan)
VALUES('$user','$g',now(),'$date','$plan')";
By
$sessAdd = "INSERT INTO training (user, groupName, sessDate, plan)
VALUES('$user','$g','$date','$plan')";
Check your table whtr field date has default CURRENT_TIMESTAMP
<html>
<head>
</head>
<body>
<form action = "insertform.php" method = "post">
field: <input type = "text" name = "fielda">
field2: <input type = "text" name = "fieldb">
thedata: <input type = "text" name = "qdata">
<input type = "submit" name = "submit">
</form>
<?php
if (isset($_POST['submit'])){
$con = mysql_connect("localhost","user","password");
if (!$con){
die("cannot connect" . mysql_error());
}
mysql_select_db("stQutieria",$con);
$sql = "INSERT INTO qtable(fielda, fieldb, qdata) VALUES ("$_POST[fielda]","$_POST[fieldb]","$_POST[qdata]")";
mysql_query($sql,$con);
mysql_close($con);
}
?>
</body>
</html>
Edit: OK! so I changed my code, I played around with double quotes or ' around the $_POST areas. When I used double quotes I got errors saying fielda / fieldb wernt defined, I also got errors saying "syntax error, unexpected '$_POST' (T_VARIABLE)"... the code i am working with derives from the same page ass insertform.php. Here is the video I am watching http://www.youtube.com/watch?v=j4FUCoCxE8w. if anyone could help me on Skype / msn / teamview I would greatly appreciate it.
You're missing quotes around your $_POST keys: $_POST[fielda] should be $_POST['fielda'] etc. (actually not true)
You need a space after your table name and opening parenthesis qtable(fielda should be qtable (fielda
You're missing a quote after '$_POST[fielda] (should be '$_POST[fielda]') and after '$_POST[fieldb] (should be '$_POST[fieldb]')
You have no error handling. If you call mysql_error() after your query you would know exactly what your error is.
You are wide open to SQL injections
You are using an obsolete API
That means your query is failing. Likely because you have no space between the table name and the column names:
INSERT INTO qtable (fielda, fieldb, qdata)
replace Your SQL with:
$sql = "INSERT INTO qtable (fielda, fieldb, qdata) VALUES ('".$_POST['fielda']."','".$_POST['fieldb']."','".$_POST['qdata']."')";
but this is really unsafe...
Much more safer is to use something like this:
$values = array($_POST['fielda'], $_POST['fieldb'], $_POST['qdata']);
$st = $db->prepare('INSERT INTO qtable (fielda, fieldb, qdata) VALUES (?,?,?)');
$st->execute($values);
You are making mistake in coding the correct sql statement will be like this one
$sql ="INSERT INTO qtable(fielda, fieldb, qdata) VALUES (".$_POST[fielda].",".$_POST[fieldb].",".$_POST[qdata].")";
Note this above sql statement is for those fields which are integer in database if fields are varchar then following will be code
$sql ="INSERT INTO qtable(fielda, fieldb, qdata) VALUES ('".$_POST[fielda]."','".$_POST[fieldb]."','".$_POST[qdata]."')";
Thank You
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):
"Connected to databaseError: 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 ''test' ('name') VALUES ('daniel')' at line 1"
The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?
Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.
HTML
<form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>
PHP (insert.php)
<?php
$dbhost = 'localhost';
$dbname = 'carbon_db';
$dbuser = 'username';
$dbpass = 'password';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if($con == FALSE)
{
echo 'Cannot connect to database' . mysql_error();
}
else
{
echo 'Connected to database';
}
mysql_select_db($dbname, $con);
$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Drop the quotes around the table name or change them to back ticks:
Change:
$sql="INSERT INTO 'test' ('name') VALUES ('$_POST[namefield]')";
To:
$sql="INSERT INTO test ('name') VALUES ('$_POST[namefield]')";
Or
$sql="INSERT INTO `test` ('name') VALUES ('$_POST[namefield]')";
It's often best to use backticks for MySQL as like any other storage engines it has it's own reserved names and it's own reserved insert practices.
try with
$sql = "INSERT INTO `test` (`name`) VALUES ('".$_POST['namefield']."')";
Change the single quotes surrounding the table name and the column name to backticks. Or get rid of them all together.
$sql="INSERT INTO `test` (`name`) VALUES ('{$_POST['namefield']}')";
Also, don't reference associative arrays ($_POST) directly in a string without using {} syntax or breaking up the string - what you have done there issues an E_NOTICE and should be avoided.
Read this thoroughly - you'd be amazed what you can (and can't) legally do in PHP strings...
try using ` instead of ' when refering to table/column names
$sql="INSERT INTO `test` (`name`)
VALUES ('$_POST[namefield]')";
Remove the single quotes around your sql statement and replace with back-tics (not sure even they are necessary):
$sql="INSERT INTO `test` ('name')
VALUES ('$_POST[namefield]')";