PHP Form to Database - php

Hi I am trying to get a form to post to a database i can connect and the database and table are set up. but rather than post the contents of the fields in it posts the text firstname and secondname in to the columns.
below is my code:
mysql_select_db("company", $conn);
$sqlCmd = sprintf("INSERT INTO names (firstname, secondname) VALUES ('%firstname','%secondname')",
mysql_real_escape_string($_POST["firstname"]),
mysql_real_escape_string($_POST["secondname"]));
//echo $sqlCmd;
//die();
mysql_query($sqlCmd);
mysql_close($conn);
}
?>
<form method="post">
<input type="text" id="firstname" name="firstname"/>
<input type="text" id="secondname" name="secondname"/>
<input name="submit" type="submit" value="Submit"/>
</form>
I need it to post the values from the fields. i am new to php and this is my first project, i would love some help.
just to add this is what i have managed after following a tutorial.
Thanks
Ryan

Do not use php's mysql_ methods any more.
It is outdated:
https://wiki.php.net/rfc/mysql_deprecation
Use mysqli_ or pdo instead
In your code you forgot the mysql_connect() anyways ;)

Just change your sprintf call to:
$sqlCmd = sprintf("INSERT INTO names (firstname, secondname) VALUES ('%s','%s')",
mysql_real_escape_string($_POST["firstname"]),
mysql_real_escape_string($_POST["secondname"]));
Also consider using the newer mysqli function: http://www.php.net/manual/en/intro.mysqli.php
HTH;
Pacific

Related

Inserting datafrom form into mysql with POST method

I havent do php for some time, but i dont really see what am I missing.
I am trying to insert some datas from FORM into MYSQL , but it still fail.
This is the file with FORM :
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<title>registrace</title>
</head>
<body>
<H1> The Best Page! </H1>
<p>
"Please registrate"
<form action="zpracovani.php" method="post">
Name <input type="text" size="20" name="Name" value=""><br>
Surname <input type="text" size="30" name="Surname" value=""><br>
Username <input type="text" size="30" name="username" value=""><br>
Password <input type="text" size="10" name="password" value=""><br>
Retype password <input type="text" size="10" name="password2" value=""><br>
<input type="image" name="button" value="submit" class="button" src="button.jpg">
</form>
</p>
</body>
</html>
As you can see i am sending data to proceed into file "zpracovani.php". I did test if i am connected to mysql server ( It passes ) and also a check if i am connected to the right database ( Also passes with no probs ).
<html>
<?php
echo "Wait please";
$con=mysql_connect ('localhost','root','');
if (!$con)
{
die ( 'Could not connect: ' . mysql_error());
}
mysql_select_db ('registrace') or die("cannot select DB");
echo #mysql_ping() ? 'true' : 'false';
$sql="INSERT INTO 'registrace'(Name, surname, username, password).
VALUES('$_POST[Name]','$_POST[Surname]','$_POST[username]','$_POST[password]')";
$result=mysql_query($sql);
if($result){
echo("<br>Input data is succeed");
}else{
echo("<br>Input data is fail");`
}
mysql_close($con);
?>
</html>
Below is overwiev of mysql table I made.
ID int(11)
Name varchar(20) latin1_swedish_ci
Surname varchar(30) latin1_swedish_ci
username varchar(30) latin1_swedish_ci
password varchar(10) latin1_swedish_ci
However I am connected to the database and to correct table it still is unable to insert anyone into the database. Can anyone look into this and help me out, please?
Thanks in advance!
Either remove the quotes in 'registrace' or use backticks in INSERT INTO 'registrace'
Example:
INSERT INTO `registrace`
Using backticks is better.
Also remove the dot in:
$sql="INSERT INTO 'registrace'(Name, surname, username, password).
It should read as:
$sql="INSERT INTO `registrace` (Name, surname, username, password)
Reformatted:
$sql="INSERT INTO `registrace` (Name, surname, username, password)
VALUES
('{$_POST['Name']}','{$_POST['Surname']}','{$_POST['username']}','{$_POST['password']}')";
Or follow this convention:
$unsafe_variable = $_POST["user-input"]
$safe_variable = mysql_real_escape_string($unsafe_variable);
mysql_query("INSERT INTO table (column) VALUES ('" . $safe_variable . "')");
NOTE: I also noticed that you are using the same name for both your DB and your table.
Make sure that this is in fact the case.
Your DB:
mysql_select_db ('registrace')
and your table?
INSERT INTO `registrace`
Plus, it would be a good idea to increase the values for your VARCHAR's and consider using MySQLi_ and prepared statements or PDO. MySQL_ functions are deprecated.
Do read the following articles:
How can I prevent SQL injection in PHP?
On owasp.org
First: use mysqli
Second: get rid of mysql ping
Third: change:
"......'$_POST[xxx]'......"
into:
"......'{$_POST['xxx']}'....."
Thanks guys it is working now.
By the way the mysql ping was just a check to see if i am well connected as i wrote in my original post :)
Anyway it was very helpful thx

php mysql_query insert into not working

<form method="post" action="updatescreen(2).php">
Name of company:<br />
<input type="text" name="artid" id="artid" size="50" /><br /><br />
<input type="submit" name="Insert" id="Insert" value="Insert" /><br /><br />
<?php
if(isset($_POST['Insert'])){
$id = $_POST['artid'];
mysql_query("INSERT INTO test (id) VALUES ('$id', )");
}
?></form>
The connection to the database is included so not mentioned here. The connection is working fine, that's not the problem.
The problem is: the php code doesn't work. The php code doesn't insert the data into my database. What's wrong?
You had a , after '$id':
mysql_query("INSERT INTO test (id) VALUES ('$id')");
Your code is also open to SQL injection. You should be using something like PDO instead of the mysql_* functions, which are deprecated. With PDO, you can guard against SQL injections by using prepared statements.
Change
mysql_query("INSERT INTO test (id) VALUES ('$id', )");
to
mysql_query("INSERT INTO test (id) VALUES ('$id')");
You have one comma too many.
mysql_query("INSERT INTO test (id) VALUES ('$id')");
In future, try printing the error, which will help you debug the problem yourself:
mysql_query("INSERT INTO test (id) VALUES ('$id')") or die(mysql_error());
And please use PDO or mysqli instead of the mysql_ functions, which are insecure and deprecated.
Try
<?php if(isset($_POST['Insert'])){
$id = $_POST['artid'];
mysql_query("INSERT INTO test (id) VALUES ('".$id."')")or die(mysql_error());
}?>
<form method="post" action="updatescreen(2).php">
Name of company:<br />
<input type="text" name="artid" id="artid" size="50" /><br /><br />
<input type="submit" name="Insert" id="Insert" value="Insert" /><br /><br />
And => think about the safety!
Errors:
mysql_query("INSERT INTO test (id) VALUES ('$id', )");
^---not secure, potencial sql injection
^----not need ","
Use this code for more security (most of all better pdo or mysqli):
if(isset($_POST['Insert'])){
$id = mysql_real_escape_string($_POST['artid']);
mysql_query("INSERT INTO test (id) VALUES ('$id')");
}

PHP FORM INSERT INTO not inserting records

I'm working on a Uni assignment and am having trouble inserting records to MySQL database using a form. My set up is below.
I can view entries in the database with no problem. I'm new to this so sorry in advance :(
conninfo.php
<?php
$strServer="localhost";
$strDatabase="djdatabase"; // CHANGE TO YOUR DATABASE NAME HERE
$strUser="root";
$strPwd=""; // Leave blank for WAMPServer
$strDB=mysql_connect($strServer,$strUser,$strPwd)or die("Could not open database");
$database=mysql_select_db("$strDatabase",$strDB);
?>
addnewdata.php
<?php include "conninfo.php";
$newdj=$_POST["dj"]; //pick up from form
$newfn=$_POST["fn"];
$newem=$_POST["em"];
$newwe=$_POST["we"];
$newpi=$_POST["pi"];
$newev=$_POST["ev"];
$query = "INSERT INTO dj(DJName, FirstName, Email, Website, Picture, EventNumber)VALUES('$newdj', '$newfn', '$newem', '$newwe', '$newpi', '$newev)";
mysql_query($query);
header("location:showall.php");
?>
enternewdata.php
<?php include "conninfo.php";?>
<html>
<head>
</head>
<body>
<form action="addnewdata.php" method="post">
DJ Name:<input type="text" name="dj"><br>
FirstName: <input type="text" name="fn" /><br>
Email: <input type="text" name="em" /><br>
Website: <input type="text" name="we" /><br>
Picture: <input type="text" name="pi" /><br>
EventID: <input type="text" name="ev" /><br>
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Many Thanks for your help :)
had better use SET command to insert data
$query = "INSERT INTO dj SET
DJName=".$newdj.",
FirstName=".$newfn.",
Email=".$newem.",
Website=".$newwe.",
Picture=".$newpi.",
EventNumber=".$newev."";
$save = mysql_query($query);
if($save){
header("location:showall.php");
}else{
die(mysql_error());
}
You are missing a quote ' wich is causing the error that you cannot see because you haven't done any debug. Anyway you should just change to this
'$newwe', '$newpi', '$newev')"; //a quote was missing after '$newv
I would suggest you to also debug query by adding or die('INVALID QUERY: ' . mysql_error());
so code would look like
mysql_query($query) or die('INVALID QUERY: ' . mysql_error());
Since you said this is an university test I don't know if you are supposed to use mysql_* function (wich are deprecated), but I would strongly reccommend to switch to mysqli or PDO if you can for security reason.
You missed ' on your query on $newev that gives you an error
$query = "INSERT INTO dj(DJName, FirstName, Email, Website, Picture, EventNumber)VALUES('$newdj', '$newfn', '$newem', '$newwe', '$newpi', '$newev)";

Using a Submit Button to insert an entry into a MySQL database via PHP?

I'm pretty new to PHP, so I'm not quite sure on what to do with this.
Basically I'm trying to insert an entry into my MySQL database, through a "submit" button in HTML. I can't seem to get this to work, is it possible?
<?php
include('db_connect.php');
$SQL = "INSERT INTO chosenitems (ID, Name, Price) VALUES ('', '4-6 Days', '£75.00')";
$result = mysql_query($SQL);
?>
The INSERT works perfectly fine on its own, but I want it to be executed when the "submit" button is pressed.
Any help would be greatly appreciated.
Thanks
Tobo.
Just set the action of the form to the URL of the script that performs the insert.
Note that since you are modifying a database, the request is probably non-idempotent and you should use the POST method.
<form action="/path/to/your/script.php" method="post">
<input type="submit">
</form>
<form method="post">
<input type="submit" name="submit" value="submt"/>
</form>
PHP
<?php
if(isset($_POST['submit']))
{
$SQL = "INSERT INTO chosenitems (ID, Name, Price) VALUES ('', '4-6 Days', '£75.00')";
$result = mysql_query($SQL);
}
?>
You can check button value is posted and can execute line of code in it.
<?php
include('db_connect.php');
if(isset($_REQUEST['SUBMIT_BUTTON_NAME']))
{
$SQL = "INSERT INTO chosenitems (ID, Name, Price) VALUES ('', '4-6 Days', '£75.00')";
$result = mysql_query($SQL);
}
?>
Hope this will be helpful to you
I had for the submit details:
<form id = "submitForm" action="config/profile_save.php" method="post">
<button type="submit" class="button" name="submit" value="submit">Save Profile</button></form>
Inside each input field on the page, I placed form = "submitForm"
I then changed the name too.(This is the super global variable later)
<input type="text" autofocus="true" class="custom_link_url_text" id="custom_link_url_text"
name="custom_link_email" placeholder="Enter your public email address" spellcheck="false"
style="width: 245px;" maxlength="75" form = "submitForm">
I was then able to capture the data on the next page using the name as POST variable.
if(isset($_POST['submit'])) {
$custom_link_email = $_POST['custom_link_email'];
}
Once I did that it was just a case of inserting data into the database.

php mysql; writing data to database

having a bit of trouble adding some data to a database. I have the file new_entry.php which is a form, which posts the data added to insert_new.php.
Every time the fields are filled in and submitted the data does not go to the database with the error message "Could not add the data to table" appearing..any ideas?
NEW_ENTRY.PHP
<body>
<form method="post" action="insert_new.php"><!-- form sent to insert_new.php-->
Section: <input type="text" name="section"/><br />
Food: <input type="text" name="food"/><br />
Description: <input type="text" name="description"/><br />
Price: <input type="text" name="price"/><br />
<br />
<input type="submit" value="submit"/>
</form>
</body>
INSERT_NEW.PHP
<?php
include 'library/connect.php';//connect to databse
$section = $_REQUEST["section"]; // get data from the HTML form on new student form
$food = $_REQUEST["food"];
$description = $_REQUEST["description"];
$price = $_REQUEST["price"];
mysql_query ("INSERT INTO food_menu (section, food, description, price) VALUES ('$section', '$food', '$description', $price)")/* insert the data to the food_menu table*/
or die ("Could not add the data to table");//error message
header('Location:index.php');//auto redirect to view page
include 'library/closedb.php';
?>
It seems that you have a mistake at the end of your MySQL query near price.
Please replace the code below with existing line:
mysql_query ("INSERT INTO food_menu (section, food, description, price) VALUES ('$section', '$food', '$description', '$price')")
Tell me the result please.
First: Don't do this. You really need to research SQL Injection or you will be very sorry.
Secondly, your price has no numeric validation (assuming it's going into a numeric column)... this is also bad... what if someone put in a dollar sign or something?
Next, please post your table definition and connection code (not the connection values).
You can also get more feedback if you do something like:
or die (mysql_error());//error message

Categories