I am currently learning SQL and have created this code for a few hours but I am unable to add data to my SQL server. Below I have provided a minimum working example of an input field and submit to SQL server. Any help is greatly appreciated. (I removed the password). I believe the problem is with isset($_POST['submit'] or before this point as the server does not seem to acknowledge the rest.
With thanks!
<html>
<body>
<table class="dd" width="100%" id="data">
<td>Field</td>
<td>:</td>
<td width="17%"><input type='textarea' name='field'/></td>
</table>
<input name='submit' type='submit' value='submit'/>
<?php
// Setting up the Database Connection
$username = "root";
$password = "";
$dbname = "table_name";
$link = mysqli_connect('localhost', $username, $password);
#mysqli_select_db($dbname);
if(isset($_POST['submit']))
{
$field = isset ($_POST['field']);
$field_f = mysql_real_escape_string($field);
$que = "INSERT INTO table_test ('fieldsql') VALUES ('$field_f')";
mysqli_query($que);
if (mysqli_query($link,$que) === TRUE) {
echo "Record added successfully";
}}
mysqli_close($link);
?>
</body>
</html>
You are missing form in your html. Without form tag your textarea and submit button wont work.
Try this :
<html>
<body>
<form method="post">
<table class="dd" width="100%" id="data">
<td>Field</td>
<td>:</td>
<td width="17%"><input type='textarea' name='field'/></td>
</table>
<input name='submit' type='submit' value='submit'/>
</form>
Also your query is wrong. Please use following query :
"INSERT INTO table_test (fieldsql) VALUES ('$field_f')";
Side note : Your query is unsafe. Read this
How can I prevent SQL injection in PHP?.
Related
I have a HTML form that (should) send the user input data to a web PHP service:
<!DOCTYPE HTML>
<html>
<head>
<title>Register Form</title>
</head>
<body>
<form action="localhost/test.php" method="POST">
<table>
<tr>
<td>Thema :</td>
<td><input type="text" name="theme" required></td>
</tr>
<tr>
<td>Jahr :</td>
<td><input type="number" name="year" required></td>
</tr>
<tr>
<td><input type="submit" value="Speichern"></td>
</tr>
</table>
</form>
</body>
</html>
The web service will enter the data into a MySQL Database. This works fine. I know that, because if I open the web service in my browser it fill a row in my database with NULL. But if I click the submit button on my HTML site it neither fill the user input nor NULL. Here's my web service:
<?php
if(isset($_POST['theme']) && isset($_POST['year'])) {
$theme = $_POST['theme'];
$year = $_POST['year'];}
$url = "127.0.0.1";
$database = "songs";
$username = "root";
$password = "";
$connect = mysqli_connect($url, $username, $password, $database);
if(!$connect)
{
die("Connection failed: ".$connect->connect_error);
}
//create a template
$sql = "INSERT INTO theme (theme, year) VALUES (?, ?);";
//create a prepared statement
$stmt = mysqli_stmt_init($connect);
//prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed";
} else {
//bind parameters to the placeholders
mysqli_stmt_bind_param($stmt, "si", $theme, $year); //1 string, 1 integer, is equal to theme and year
//run parameters inside database
mysqli_stmt_execute($stmt);
mysqli_close($connect);
}
?>
I know that my HTML site is working, because on webhook.site it shows me the input. (Please ignore missing error handling and everything on my web service, I know that.)
What am I doing wrong?
In the form tag , the value of action should be test.php if both html and the file are in same folder. Otherwise put the relative path. Not localhost/test.php.
i am using php for inserting data in in mysql database. i am new to php and also mysql please help
<html>
<head>
<title>create menu</title>
</head>
<h1 align="center">create menu</h1>
<h2 align="center">Dont create more than 7 menu</h2><br/><br/>
<form method="post">
<table border="2px" width="500px">
<tr>
<th colspan="2" align="center">create menu</th>
</tr>
<tr>
<td align="right">menu name</td>
<td><input type="text" name="menu"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="create"></td>
</tr>
</table>
</form>
<?php
mysql_connect("localhost","root","");
mysql_select_db("coupons");
if(isset($_POST['submit'])){
$menu=$_POST['menu'];
$query = "insert into menu(item) values ('$menu')";
if(mysql_query($query)){
echo "<h1 align='center'>DATA INSERTED</h1>";
}
else{
echo "<h1>data not inserted</h1>";
}
}
?>
where am i wrong please help data is not inserting to database
First thing which version of php you are using, because mysql_connect() is not supported in newer version of php.
If your php version doesn't support this function you should get error on submit.
so i suggest you to replace mysql_xxx with mysqli_xxx (as you can see here mysql_connect)
replace these 2 lines
mysql_connect("localhost","root","");
mysql_select_db("coupons");
with these lines of code
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"coupons");
And
update if condition with this mysqli_xxx() as
if(mysqli_query($query))
For more detail please read mysqli_connect
you can do like this, for your php code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "coupons";
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query=$conn->prepare("INSERT INTO menu( item) VALUES( :menu)");
$query->bindParam(':menu',$menu);
$menu=$_POST['menu'];
$query->execute();
echo "<h1 align='center'>DATA INSERTED</h1>";
}
catch(PDOException $e)
{
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
echo "<h1>data not inserted</h1>";
}
$conn = null;
?>
Your code is working absolutely fine. I tried it on my system. Check the screenshot -
HTML form submission result -
Value in database -
Possible errors on your system -
MySql is not running.
Database name is incorrect
You have not provided the password
I have problem to get my code working in php
I want to move data from a form in html to my mysql database but it dont work??
Form part
<form action ="Mydbsinsertpersson4.php" method='POST'>
<table>
<tr><td width='100'>För namn:<input type='text' name='fnamn'><td></tr>
<tr><td width='100'>Efternamn:<input type='text' name='enamn'><td></tr>
</table>
<tr><td><input type='submit' name='Submit' value='Submit'><td></tr>
</form>
the php part
<?php
if(isset($_POST["submit"])){
require_once 'Mydbconfig.php';
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO tpersson (Perfnamn, Perenamn)
VALUES ('".$_POST["fnamn"]."','".$_POST["enamn"]."')";
$conn = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
the connection to my mysql database works i can get data from the database but not input to it.
Thanks in the advanced.
This is on of many solutions i have tried non have worked!!
The problem is :-
<tr><td><input type='submit' name='Submit' value='Submit'><td></tr>
And you write:-
if(isset($_POST["submit"])){
Note:- either change name = submit in first one or change $_POST["Submit"] in second one. Thanks.
I like to do this using two files, one for handling the inputs and one for the actual form.
form.html:
<form action ="/assets/post_people.php" method='POST'>
<table>
<tr><td width='100'>Firstname:<input type='text' name='fname'><td></tr>
<tr><td width='100'>Lastname:<input type='text' name='lname'><td></tr>
</table>
<tr><td><input type='submit' name='Submit' value='Submit'><td></tr>
</form>
Now, for post_people.php:
<?php
//db
require_once 'db_connect.php';
//Get and filter input # to avoid injections
$Firstname = mysql_real_escape_string($_POST['fname']);
$Lastname = mysql_real_escape_string($_POST['lname']);
//Check if the user has submitted the form
if(isset($_POST['Submit'])){
//Check if the person already exist in our database
$Check_people = mysql_query("SELECT * FROM People WHERE Firstname = '$Firstname' AND Lastname = '$Lastname'");
if(mysql_num_rows($Check_people)==1){
//The person already exists with exact same data!
}
//The person did not exist in our database, so we'll update.
else{
$update_query = mysql_query("INSERT INTO People (Firstname, Lastname) VALUES ('$Firstname', '$Lastname')");
if($update_query){
//success
}
else {
//Error
}
}
mysql_close();
}
//The user didnt submit the form and tried to access the file ?
//Redirect to /form.html & kill the script.
else{
header("Location: /form.html");
die;
}
I don't know if this will work for you, but it did work for me :)
(Yes im well aware that you shouldn't use mysql_ functions as they are depreciated but they are still working and are easy to use :))
Errors
Incorrect in submit tag name name='Submit'
improve your HTML codeing format(</table> tag should close after last </tr> tag)
Avoid SQL Injections by using mysql_real_escape_string()
So your final code would be
<form action ="Mydbsinsertpersson4.php" method='post'>
<table>
<tr><td width='100'>För namn:<input type='text' name='fnamn'><td></tr>
<tr><td width='100'>Efternamn:<input type='text' name='enamn'><td></tr>
<tr><td><input type='submit' name='submit' value='Submit'><td></tr>
</table>
</form>
In Mydbsinsertpersson4.php
<?php
if(isset($_POST["submit"])){
require_once 'Mydbconfig.php';
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$fname = $mysqli->real_escape_string($_POST["fnamn"]);
$ename = $mysqli->real_escape_string($_POST["enamn"]);
$sql = "INSERT INTO tpersson (Perfnamn, Perenamn) VALUES ('$fname','$ename')";
$conn = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
I was hoping someone could help me with a small script I am writing, my main goal is to just make a registration page as secure as possible and thought the best place to start would be using mysql_real_escape_string however it wont keep I just keep getting error at line 1 so here's my code:
<?php
if(isset($_POST['submit'])){
if($_POST['username'] == "" || $_POST['password'] == ""){
header("Location: tryagain.php");
exit;
}else{
mysql_connect("localhost", "root", "Root") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$username = $_POST['username'];
$password = $_POST['password'];
$sql = sprintf("INSERT into login(id,username,password) values('','%s','%s'", mysql_real_escape_string($username), mysql_real_escape_string($password));
$result = mysql_query($sql) or die(mysql_error()) ;
echo "Congratulations it worked woooo";
}
}
?>
and heres the html
<form method="post" action="sql.php">
<table>
<tr>
<td>
<input type="text" name="username"/>
</td>
<td>
<input type="text" name="password"/>
</td>
<td>
<input type="submit" name="submit" value="submit">
</td>
</tr>
</table>
</form>
If i change the $sql statment to this the code works fine
$sql = "INSERT into login(id,username,password) values('','$username','$password')";
Can anyone see what I've done wrong :S it works perfectly fine when I adjust it to log in using real escape.
Also what other methods can I use to validate data? I plan on making the if statements check for only number and letters, and just prevent any special characters all together. Thanks.
On a side note, yes I know mysqli and pdo should be used not mysql sadly were I'm at they don't use them.
Your SQL statement is broken:
INSERT into login(id,username,password) values('','%s','%s'
Should be
INSERT into login(id,username,password) values('','%s','%s')
Not sure what is your issue, I'm thinking sprintf. Maybe try this :
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$sql = sprintf("INSERT into login(id,username,password) values('','%s','%s', $username, $password)");
Can someone look over my code and let me know what's wrong with it?
The problem I'm having is that when I enter text to the 3 fields and hit submit, it doesn't insert to my database (mysql, with phpmyadmin as gui). No error messages or anything; it simply doesn't insert the data..
I have looked over the code over and over, and I can't pin point what's wrong with it.
//---------------------------This is my index.php------------------------------
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Web Bar Title</title>
<link rel="stylesheet" href="styles.css" type="text/css" />
</head>
<body>
<?php
if(isset($_POST['Submit']))
{
include 'connectdb.php';
include 'openconnection.php';
$first = $_POST['first'];
$second = $_POST['second'];
$third = $_POST['third'];
$query = "INSERT INTO details (first, last, third) VALUES('$first','$second','$third');";
mysql_query($query) or die('Error, insert query failed');
}
?>
<div id="page">
<tbody>
<form method="post">
<table>
<tr>
<td ><b>First</b></td>
<td><input name="first" type="text" id="first"></td>
<tr>
<tr>
<td ><b>Second</b></td>
<td><input name="second" type="text" id="second"></td>
<tr>
<td ><b>Company</b></td>
<td><input name="third" type="text" id="third" > </td>
</tr>
</table>
<input name="submit" type="submit" id="submit" value="Submit" />
</form>
</body>
</html>
</tbody>
</div>
//---------------------------------connectdb.php------------------------------------------
<?php
$dbhost = 'localhost';
$dbuser = 'sharkk';
$dbpass = 'pw';
$dbname = 'test';
?>
//---------------------------------openconnection.php-------------------------------------
<?php
$dbhost = 'localhost';
$dbuser = 'sharkk';
$dbpass = 'pw';
$dbname = 'test';
?>
<?php
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname) or die ('No Selection of Database');
?>
EDIT: It would be easier and faster to communicate via MSN/AIM/Steam/Skype, if anyone has any of those!
Change your top line to
if( isset( $_POST['submit'] ) ) {
I can't remember if it is case sensitive or not
Better still change it to
if($_SERVER['REQUEST_METHOD'] == 'POST')
The isset() method on the submit button is unreliable because Internet Explorer will not send the submit button as a post variable if the user presses the enter key to submit the form, and thus your code will not detect a form submission.
Just check MYSQL INSERT query in Your own MySQL platform, by simply copying your INSERT query and paste in your MySQL database, and check there. it wil report your fault.
If I'm right, then your problem lies on your INSERT query part. You have stated :
$query = "INSERT INTO details (first, last, third) VALUES('$first','$second','$third');";
In the above part, there shouldn't be 2 semicolons, Jus one is enough... it wil look like :
$query = "INSERT INTO details (first, last, third) VALUES('$first','$second','$third')";
Also, check ur include part too...
it shouldnt be :
include 'connectdb.php'; //braces r missing
include 'openconnection.php'; // braces r missing
it should be :
include ('connectdb.php');
include ('openconnection.php');
I hope this may do good fa U ....
CHEERS buddy.........
Try putting the values between double quotes instead of single quotes
VALUES("$first","$second","$third")