we are working on a school project. We are trying to use some simple MySQL to store data from a single HTML text form into a MySQL database.
My HTML looks like this:
<form action="sql/tilmeld-sms.php" method="post">
<h2>Tilmelding til SMS:</h2>
<input type="text" name="sms">
<input type="submit" value="Submit">
</form>
Our SQL looks like this:
<?php
$connect = mysql_connect(“localhost”, “ODBC”, “”); if (!connect) { die('Connection Failed: ' . mysql_error()); { mysql_select_db(“database_name”, $connect);
$user_info = “INSERT INTO sms (sms) VALUES ('$_POST[sms]')”; if (!mysql_query($user_info, $connect)) { die('Error: ' . mysql_error()); }
echo “Your information was added to the database.”;
mysql_close($connect);
?>
When we run this on our localhost, we get a syntax error on line 4. Which means there is something wrong with this line of code:
$user_info = “INSERT INTO sms (sms) VALUES ('$_POST[sms]')”; if (!mysql_query($user_info, $connect)) { die('Error: ' . mysql_error
We know this is very simple MySQL. But its the first time we use it, and the first time we try to store data from a HTML form into a mysql database.
Other info:
Databasename: projekt32
Databasehost: localhost
Username: ODBC (We read this is the general username for localhost on
Windows)
Password: no password on localhost we read
Tablename: sms
EDIT: This is the error code we get:
Parse error: syntax error, unexpected 'INTO' (T_STRING) in C:\xampp\htdocs\projekt-3-2\sql\tilmeld-sms.php on line 4
EDIT2: This is a school project, and MySQL is part of this project. We wont pass without using it, so suggesting other things we can do than MySQL wont work but thanks anyway!
You are using back ticks instead of double quotes/single quotes.
UPDATED:
$connect = mysql_connect('localhost', 'ODBC', '');
if (!connect) {
die('Connection Failed: ' . mysql_error());
} // ALSO Use } instead of { here.
mysql_select_db('database_name', $connect);
ALSO,
$user_info = "INSERT INTO sms (sms) VALUES ('".$_POST['sms'] ."')";
Try this
<label for="sms">SMS</label>
<input id="sms" type="text" name="sms" />
<input type="submit" name="add" id="add" value="Go">
$sms = kontroll_form_data_string($_POST['sms'], 100);
if ( isset( $_POST['add'] ) ) {
$db = mysql_connect('localhost', 'ODBC', '');
mysql_select_db("projekt32") or die(mysql_error());
$insert = "INSERT INTO sms(sms) VALUES('$sms')";
if(mysql_query($insert)) {
echo("Done");
}
}
I think , you should try "mysql_real_escape_string", Concrete example of where mysql_real_escape_string fails and Prepared Statements are necessary
$connect = mysql_connect(“localhost”, “ODBC”, “”); if (!connect) { die('Connection Failed: ' . mysql_error()); { mysql_select_db(“database_name”, $connect);
$sms = mysql_real_escape_string($_POST[sms]);
$user_info = “INSERT INTO sms (sms) VALUES ('$sms')”; if (!mysql_query($user_info, $connect)) { die('Error: ' . mysql_error()); }
echo “Your information was added to the database.”;
mysql_close($connect);
I hope this helps you.
Related
I'm Not so good about PHP, I m still learning that language, so I have made Form which one will add data to mysql using PHP and Method POST. But in when i click on submit nothings happens in the database, no data added.
This is config.php
$SETTINGS["hostname"]='localhost';
$SETTINGS["mysql_user"]='username';
$SETTINGS["mysql_pass"]='passw';
$SETTINGS["mysql_database"]='database';
$SETTINGS["data_table"]='defaulttable'; // this is the default database name that we used
/* Connect to MySQL */
if (!isset($install) or $install != '1') {
$connection = mysql_connect($SETTINGS["hostname"], $SETTINGS["mysql_user"], $SETTINGS["mysql_pass"]) or die ('Unable to connect to MySQL server.<br ><br >Please make sure your MySQL login details are correct.');
$db = mysql_select_db($SETTINGS["mysql_database"], $connection) or die ('request "Unable to select database."');
};
?>
and here is my HTML FORM
<form action="insert.php" method="post">
<li>Place Name: <input type="text" name="plname" /></li>
<li>City: <input type="text" name="plcity" /></li>
<li>Address: <input type="text" name="pladdress" /></li>
<li>Terminal QTY: <input type="number" name="plqty" /></li>
<li><input type="submit" name="save" value="Add Place" /></li>
And What About insert.php
<?php
include ("config.php");
$current_user = wp_get_current_user();
$UserID = $current_user->user_login ;
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
//$sql="INSERT INTO wp_telemetry_place (plUserID, plName, plCity, plAddress, plTerminalQ) VALUES ('".$UserID."','".$_POST['plname']."','".$_POST['plcity']."','".$_POST['pladdress']."','".$_POST['plqty']."')";
$sql = "INSERT INTO wp_telemetry_place (plUserID, plName, plCity, plAddress, plTerminalQ) VALUES ('{$UserID}','{$_POST['plname']}','{$_POST['plcity']}','{$_POST['pladdress']}','{$_POST['plqty']}')";
if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
mysqli_close($connection);
?>
And when I klick to Button for add data, it does not works. No Errors, No Data updated or added in mysql database. What about Passwords, Host, Usernames, Table names etc... I Checked twice :( I would appreciate any helps from your side guys, Thanks in advance and SORRY FOR MY BAD ENGLISH
Your SQL query is not formatted properly. Try this:
$sql = "INSERT INTO wp_telemetry_place (plUserID, plName, plCity, plAddress, plTerminalQ) VALUES ('{$UserID}','{$_POST['plname']}','{$_POST['plcity']}','{$_POST['pladdress']}','{$_POST['plqty']}')";
Your query is probably giving you an error message, but you have a typo in your code, replace $conn with $connection to read it, like so:
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
Finally, and this is important, the way you're writing your code is hugely dangerous, because you're accepting user input without any filtering. I recommend you google SQL injection to learn more about it.
The main Problem was 'i' I changed
if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);}
to
if (mysql_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error($connection);}
Now it works perfect, Just I need to look at SQL Injection thats all. Thank you guys anyway :))
A HTML form has been created that should (when filled) send the data it's holding to a database inserting a new row so it can be used later on. However, I can't seem to get it to work, I'm getting the following error:
Notice: Use of undefined constant con - assumed 'con' in C:\xampp\htdocs\form\insert.php on line 4
Warning: mysql_query() expects parameter 1 to be string, object given in C:\xampp\htdocs\form\insert.php on line 17
Data not inserted
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Form linked to database</title>
</head>
<body>
<form action="insert.php" method="post">
Name: <input type="text" name="username">
<br>
Email: <input type="text" name="email">
<br>
<input type="submit" value="insert">
</form>
</body>
</html>
PHP Code
<?php
$con = mysqli_connect('localhost','[retracted]','[retracted]');
if(!con) {
echo 'Not connected to server!';
}
if(!mysqli_select_db($con,'tutorial')) {
echo 'Database not selected!';
}
$Name = $_POST['username'];
$Email = $_POST['email'];
$sql = "INSERT INTO person (Name,Email) VALUES ('$Name','$Email')";
if(!mysql_query($con,$sql)) {
echo 'Data not inserted';
} else {
echo 'Data inserted';
}
//header("refresh:2; url=form.html");
?>
I'm new to PHP and followed the following YouTube tutorial.
I'm also using XAMPP for this, on a localhost. Any help is appreciated. Thank you.
You should change:
if(!con){
echo 'Not connected to server!';
}
to:
if(!$con){
echo 'Not connected to server!';
}
as you're missing a dollar sign there.
Additionally, you're using a mysql_ function here, on the mysqli_ object $con:
if(!mysql_query($con,$sql))
Change this to
if(!mysqli_query($con,$sql))
SQL injection
As your query is vulnerable to SQL injection, then I'd like to recommend you take a look at using prepared statements, or using mysqli_real_escape_string()-- though, this comes with a few gotcha's: https://stackoverflow.com/a/12118602/7374549
You have done two small mistakes ie
1) forgot to add $ before the variable name ie changes is
if(!$con){
echo 'Not connected to server!';
}
2) you are connected with mysqli_connect but you are trying to use mysql_query functions in it. so please change and use mysqli_query
if(!mysqli_query($con,$sql)){ }
This is issue in your case. My suggestion is to use mysqli or PDO that is good practice.
You are not using the correct mySQL query function, you have used:
mysql_query($con
You should use:
mysqli_query
instead. Let me know if you still have issues.
Altough you have a lot of answers right now, I think none of those is the right one. I've written your code new, procedural as you did, but with prepared statements, so you're going to be save to SQL injections.
<?php
$con = mysqli_connect('localhost','[retracted]','[retracted]');
if(!$con){
echo 'Not connected to server!';
}
if(!mysqli_select_db($con,'tutorial')){
echo 'Database not selected!';
}
$Name = $_POST['username'];
$Email = $_POST['email'];
if ($stmt = mysqli_prepare($con, "INSERT INTO person (Name, Email) VALUES (?, ?"))) {
mysqli_stmt_bind_param($stmt, "ss", $Name, $Email);
mysqli_stmt_execute($stmt);
echo "Data inserted";
}
else {
echo "Error";
}
mysqli_close($con);
//header("refresh:2; url=form.html");
?>
I think it should work, if not let me know.
Try this :
<?php
// Create connection
$conn = new mysqli("localhost", "username", "password", "databasename");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('test fname', 'test lname', 'test#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I need to connect an html form to my sql database and I'm starting out with a simple form so I can understand how it works. I can't figure out what I am doing wrong. I have the form created, the php script, and the database created. Whenever I submit the form it takes me to a blank page and nothing has been added to my database. I've written error messages if the connections fail but I'm not seeing those either. I'm not as advanced in programming can someone please help me?
index1.html
<html>
<body>
<form action="info.php" method="post">
<p>Username:<input type="text" name="username" /></p>
<p>Email:<input type="text" name="email" /></p>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
info.php
<?php
define('DB_NAME' , 'users' );
define('DB_USER' , 'root');
define('DB_PASSWORD' , '');
define('DB_HOST' , 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
//connection to host
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//error if not connected to host
$db_selected = mysql_select_db(DB_NAME, $link);
//select the database
if(!$db_selected){
die('Can\'t use ' . DB_NAME . ':' . mysql_error());
}
echo 'Connected successfully';
$value = $_POST['username'];
$value2 = $_POST['email'];
$sql = "INSERT INTO guests (username, email) VALUES ('$value', '$value2')";
if(!mysql_query($sql)){
die('Error: ' . mysql_error());
}
//error check to see if connected to tables
mysql_close();
//close connection
?>
As I stated in comments; your mysql_ code checks out, so chances are you need to use either mysqli_ or PDO, since mysql_ functions may very well not be available for you to use.
If the following mysqli_ rewrite does not work for you, then the problem goes deeper and would be out of scope of the question.
Using error reporting will/should confirm that. Consult "Footnotes" on how to use it in your PHP file(s).
<?php
define('DB_NAME' , 'users' );
define('DB_USER' , 'root');
define('DB_PASSWORD' , '');
define('DB_HOST' , 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//connection to host
if (!$link) {
die('Could not connect: ' . mysqli_error($link));
}
echo 'Connected successfully';
$value = mysqli_real_escape_string($link,$_POST['username']);
$value2 = mysqli_real_escape_string($link,$_POST['email']);
$sql = "INSERT INTO guests (username, email) VALUES ('$value', '$value2')";
if(!mysqli_query($link, $sql)){
die('Error: ' . mysqli_error($link));
}
//error check to see if connected to tables
else{
echo "Data entered";
}
mysqli_close($link);
//close connection
?>
References:
MySQLi: http://php.net/manual/en/book.mysqli.php
PDO: http://php.net/manual/en/ref.pdo-mysql.php
Error reporting: http://php.net/manual/en/function.error-reporting.php
Footnotes:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Make sure your server is running and properly configured for PHP/MySQL/Apache.
Make sure your columns are indeed VARCHAR and long enough to accommodate the data.
Try this query:
INSERT INTO guest set username=$value1,email=$value2
hope it will solve .
Try this, it should work for you.
$sql = "INSERT INTO guests (username, email) VALUES (".$value.", ".$value2.")";
I have a simple html form and a php file to execute a database insertion. The problem I am having is that when I press the submit button, my database table receives 3 copies of the same submission and I only need one. Below is the code.
html:
<!DOCTYPE html>
<html>
<form action="demo.php" method="post">
<p>
Input 1: <input type="text" name="input1" />
<input type="submit" value="Submit" />
</p>
</form>
</html>
php:
<?php
define('DB_NAME', 'phpmyadminName');
define('DB_USER', 'phpmyadminUser');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected){
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value = $_POST['input1'];
$sql = "INSERT INTO demo (input1) VALUES ('$values')";
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
mysql_close();
?>
The DB_NAME, DB_USER, and DB_PASSWORD have all been changed for obvious reasons, but the code does work.
It just submits too many copies of the form data to the database table. Way back when I was in school, I had this issue, but it seemed like the problem was on the server's end and not our code. The server used here is mine and I do have full control over it. If the server is the issue at fault, I need help correcting that (as I am doing this to learn how to admin these tools, I do not know much more than basic level administration).
Kenneth, the code you have provided here honestly needs some work. First of all, please don't use the mysql API anymore. It's deprecated, will no longer be supported in future PHP versions, and is insecure. For all database operations use the mysqli or PDO API's, preferrably with prepared statements.
Secondly, do not ever INSERT $_POST or $_GET variables directly into the database without validating/sanitizing them first as someone could delete your data or even worse your whole database. PHP has numerous functions to make this very easy such as ctype depending on the data type.
Maybe try something like this in your code:
if (!empty($_POST['input1'])) { //checks if data was received//
$value = $_POST['input1'];
mysql_real_escape_string($value);
$sql = "INSERT INTO demo (input1) VALUES ('$value')";
} else {
echo "form was not received";
exit;
}
I also noticed that your variable names were different, which is corrected above.
EDIT :
Mistakenly used wrong syntax for PHP ctype function.
You are taking the POST input value in the variable named $value and in query you are sending $values
I have corrected the code.
Can you please try the below code
<?php
define('DB_NAME', 'phpmyadminName');
define('DB_USER', 'phpmyadminUser');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected){
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value = $_POST['input1'];
if($value!=''){
$sql = "INSERT INTO demo (input1) VALUES ('".$value."')";
}
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
mysql_close();
?>
Below is correct code for the issue. I have checked that when you refresh your page it will create new blank entry in database and also the variable name is wrong.
You have to check for the Request method. This
$_SERVER['REQUEST_METHOD'] === 'POST'
will check the form method and it will prevent the blank entries in database.
<?php
define('DB_NAME', 'test');
define('DB_USER', 'root');
define('DB_PASSWORD', 'mysqldba');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected){
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
//Test for request method
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$value = $_POST['input1'];
$sql = "INSERT INTO demo (input1) VALUES ('$value')";
//echo $sql;die;
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
}
mysql_close();
?>
I am trying to get my sql to post information from a html form into my database however keep getting:
( ! ) SCREAM: Error suppression ignored for
( ! ) Notice: Undefined index: firstname in C:\wamp\www\insert.php on line 29
Call Stack
# Time Memory Function Location
1 0.0005 247624 {main}( ) ..\insert.php:0
The code i am using is:
<form action="insert.php" method="post">
Name: <input type="text" name="firstname">
<input type="submit" value="Submit">
</form>
<?php
// This is the connection to my database
$con = mysql_connect('127.0.0.1', 'shane', 'diamond89');
if (!$con){
die('Could not Connect: ' . mysql_error());
}
// This selects which database i want to connect to
$selected = mysql_select_db("shane",$con);
if (!$con){
die("Could not select data");
}
// This inserts new information to the Database
$name = $_POST['name'];
$query = "INSERT INTO test1 VALUES('id', '$name')";
mysql_query($query) or die('Error' . mysql_error());
// This closes my connection
mysql_close($con)
?>
Your form has an input named firstname not name, so $_POST['name'] should be $_POST['firstname']
change
// This inserts new information to the Database
$name = $_POST['name'];
to
// This inserts new information to the Database
$name = $_POST['firstname'];
Name:
<?php
// This is the connection to my database
$con = mysql_connect('127.0.0.1', 'shane', 'diamond89');
if (!$con){
die('Could not Connect: ' . mysql_error());
}
// This selects which database i want to connect to
$selected = mysql_select_db("shane",$con);
if (!$con){
die("Could not select data");
}
if($_POST['firstname'])
{
// This inserts new information to the Database
$name = $_POST['firstname'];
$query = "INSERT INTO test1 VALUES('id', '$name')";
mysql_query($query) or die('Error' . mysql_error());
// This closes my connection
mysql_close($con)
}
?>
The first time you view your page, $_POST is undefined as the form hasn't been posted.
Once the user submits, the $_POST will be valid.
You should try to see if the values exists before using it.
eg
if (isset($_POST['xxx']))
{
/* Do Something */
}
Are you getting values after submit the form?. Try:
<?php
print_r($_POST);
?>
I upvoted the answer by AB Åttìtúðê Þêrfëçt that corrects your PHP code. However, this might help:
Through wamp tray icon, open php.ini file and find
error_reporting = E_ALL
Replace w/
error_reporting = E_ALL & ~E_NOTICE
Then save file and restart wamp
From: http://forum.wampserver.com/read.php?2,72161,72201
Thank you for all of your help i worked this out with a bit of hair pulling. I came up with
<?php
// This is the connection to my database
$con = mysql_connect('127.0.0.1', 'shane', 'diamond89');
if (!$con){
die('Could not Connect: ' . mysql_error());
}
// This selects which database i want to connect to
$selected = mysql_select_db("shane",$con);
if (!$con){
die("Could not select examples");
}
$name=$_POST['firstname'];
$sql="INSERT INTO test1(name)VALUES('$name')";
$result=mysql_query($sql);
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='sql_table.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
// This closes my connection
mysql_close($con)
?>