I have this problem with phpMyAdmin. I've set up my simple php and mysql scripts and everything works fine. It connects to my mysql database(remote with my hosting provider) and it does actually insert all the required fields into the database. the problem is that the fields are all blank. there is nothing in them. here is my code:
<?php
$con = mysql_connect("myserverip","mydatabasename","my password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydatabasename", $con);
$sql="INSERT INTO nametable (firstname, lastname) VALUES('$_POST[firstname]','$_POST[lastname]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
The html is very simple, just two input fields with first name and last name:
The html:
<html>
<body>
<h1>A small example page to insert some data in to the MySQL database using PHP</h1>
<form action="insert.php" method="post">
Firstname: <input type="text" name="fname" /><br><br>
Lastname: <input type="text" name="lname" /><br><br>
<input type="submit" />
</form>
</body>
</html>
All help is appreciated.
Because you have enclosed your $_POST variables in single quotes ('), PHP is treating them as strings rather than as arrays, so the data is not being pulled from them. Your query should look something like this:
$sql = "
INSERT INTO
nametable (firstname, lastname)
VALUES
('" . $_POST['firstname'] . "', '" . $_POST['lastname'] . "')";
(whitespace added for readability)
Also, as some other users have pointed out, the mysql extension for PHP has been deprecated so it should not be used. Furthermore, the way your are building your query opens you up to something called SQL injection, which is very dangerous.
If this code is just for fun then that's fine, but you should not upload this to a production server under any circumstances.
Related
Hey there im currently try to create a page where I can insert some information into my SQL database, this is the php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "film";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$filmtitle = $_POST['filmtitle'];
$filmyear = $_POST['filmyear'];
$filmduration = $_POST['filmduration'];
$filmrating = $_POST['filmrating'];
$sql="INSERT INTO film (Title, FilmYear, Duration, FilmRating) VALUES
('$filmtitle', `$filmyear`, '$filmduration', '$filmrating',)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When I hit the submit button I get the following error,
Object not found!
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.
If you think this is a server error, please contact the webmaster.
Here is the HTML as well
<html>
<body>
<h1> Insert a new film!</h1>
<form action ="insert-film.php method="post">
Film Title: <input type="text" name="filmtitle">
Year: <input type="text" name="filmyear">
Duration: <input type="text" name="filmduration">
Certificate: <input type="text" name="filmcertificate">
<input type="submit">
</form>
</body>
</html>
There's a few things wrong here.
First
<form action ="insert-film.php method="post">
^ right there.
is missing a quote.
<form action ="insert-film.php" method="post">
Then this: you used ticks instead of quotes for $filmyear and a trailing comma
('$filmtitle', `$filmyear`, '$filmduration', '$filmrating',)";
^ right there.
which should read as
('$filmtitle', '$filmyear', '$filmduration', '$filmrating')";
You also seem to be using the wrong array for filmcertificate which should be filmrating.
Certificate: <input type="text" name="filmcertificate"> there is no POST array for it.
$filmtitle = $_POST['filmtitle'];
$filmyear = $_POST['filmyear'];
$filmduration = $_POST['filmduration'];
$filmrating = $_POST['filmrating'];
and
Film Title: <input type="text" name="filmtitle">
Year: <input type="text" name="filmyear">
Duration: <input type="text" name="filmduration">
Certificate: <input type="text" name="filmcertificate">
The last one does not match the $_POST['filmrating'] array.
You probably meant to do:
Film Title: <input type="text" name="filmtitle">
Year: <input type="text" name="filmyear">
Duration: <input type="text" name="filmduration">
Film rating: <input type="text" name="filmrating">
Only you know what that should be. Ajust accordingly.
Once your PHP kicks in after fixing the quote in the action, you would have been thrown an undefined index filmrating in line... notice.
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);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.
You have an extra comma at the end of your sql:
$sql="INSERT INTO film (Title, FilmYear, Duration, FilmRating) VALUES
('$filmtitle', `$filmyear`, '$filmduration', '$filmrating',)";
should be:
$sql="INSERT INTO film (Title, FilmYear, Duration, FilmRating) VALUES
($filmtitle', '$filmyear', '$filmduration', '$filmrating')";
Also, make sure you are consistent with your backticks versus single quotes.
Finally, you are exposed to SQL injection attack.
I am trying to post some data from my HTML form into my mysql database.
Here is my HTML code:
<!doctype html>
<html>
<head>
</head>
<body style="background-color:#BCB7B7">
<form id="form1" name="form1" method="post" style="text-align:center" action="post.php">
<input type="text" name="name" id="name" placeholder="Name">
<p></p>
<input type="text" name="age" id="age" placeholder="Age">
<p></p>
<input type="text" name="food" id="food" placeholder="Food">
<p></p>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</body>
</html>
and here is my php code:
<?php
$connect = mysql_connect("localhost","myusername","mypassword","mydbname");
mysql_select_db("mydbname",$connect);
mysql_query("INSERT INTO myTable VALUES Name = $_POST[name], Age = $_POST[age], Food = $_POST[food]");
?>
but the data does not get saved
Strings in SQL must be quoted. You are dumping your variables into the SQL without quotes.
Your syntax is also wrong. The format is INSERT INTO table_name (column_name, column_name) VALUES value, value.
You are also failing to escape the data, so you are vulnerable to SQL Injection attacks.
To fix your problems:
Stop using the deprecated mysql_ library and switch to mysqli_ or PDI
Use bound arguments to insert variables into your SQL
Use the correct syntax
This question about preventing SQL injection has examples of how to use those libraries safely.
There are 2 different versions of the INSERT command - you are using neither.
Either:
INSERT INTO myTable SET Name = "Peter",
Age = 15, Food = "pizza"
or
INSERT INTO myTable (Name, Age, Food) VALUES
("Peter", 15, "pizza")
You have to quote the values:
mysql_query("INSERT INTO myTable VALUES Name = '$_POST[name]', Age = '$_POST[age]', Food = '$_POST[food]'");
Hint: You should use mysqli_ or PDO_ functions as mysql_ functions are deprecated
try this
<?php
$connect = mysql_connect("localhost","myusername","mypassword","mydbname") or die("error while connecting to the database");
mysql_select_db("mydbname",$connect) or die("error while selecting the database");
mysql_query("INSERT INTO myTable VALUES ('" . mysql_real_escape_string($_POST[name]) . "', '" . mysql_real_escape_string($_POST[age]) . "', '". mysql_real_escape_string($_POST[food]) . "')");
?>
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
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)";
Hi i am using openWYSIWYG as a text editor for a text area. I then am trying to post the contents of the text area to a field in my database.
This is the code i have so far -
<?php
$text = $_GET['Comments'];
mysql_connect ("localhost", "user", "password") or die ('Error: ' . mysql_error());
mysql_select_db("databasename") or die ('Data error:' . mysql_error());
$query="INSERT INTO KeepData (player_data)VALUES ('$text')";
mysql_query($query) or die ('Error updating database' . mysql_error());
?>
I can connect to the database, and when i click submit it adds a blank entry into the field? how would i get it so it keeps all the formatted data?
Many thanks
update
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<textarea id="Comments" name="Comments">
example text
</textarea>
<input type="submit" name="mysubmit" value="Save Post" />
</form>
DIM3NSION
Try something like the following:
<?php
if ($_POST['submit']) {
mysql_connect ("localhost", "user", "password") or die ('Error: ' . mysql_error());
mysql_select_db("databasename") or die ('Data error:' . mysql_error());
$text = mysql_real_escape_string($_POST['comments']);
$query="INSERT INTO KeepData (player_data) VALUES ('$text')";
mysql_query($query) or die ('Error updating database' . mysql_error());
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<textarea name="comments">Example Comment</textarea>
<input name="submit" type="submit" value="submit" />
</form>
You must save an format coded version elsewhere on a hidden textarea (much like here on StackOverflow, if you type **text** it will come out as text, in the database, they probably save it as **text** and render it with PHP.
Once the formatted version is saved, render it with PHP when you get the data from the database.
Is your form POSTing or GETing (you said POSTing in your post)? You have $_GET['Comments'], but if your form's action is POST, you need to use $_POST['Comments'];
if you add echo $text;exit; after you assign $text, do you see anything?
You should use mysql_escape_string function because of mysql injection and if text contains ' you'll get error.
Check if your have <form action='get'>. If it is just <form> get used by default
Check that your wisywig have name='Comments' attribute.
Escape the $text with mysql_real_escape_string. It can contain SQL-illegal symbols, like '. This function escapes them with \
(recommendation) do not use mysql_*, it is deprecated of PHP 5.3 and will be removed.
(recommendation) appending user input to sql query is always a risk of SQL-injection. Use prepared statements
just add the onclick event something like
<button onclick=" $('#txtEditor').val($('.Editor-editor').html());" type="Publish" id="Publish" name="Publish" class="btn btn-primary">Publish</button>
remember the #txtEditor has to match with the form id, this works well, and note the .html will save it to database with the color,Bold and many more effect if you added any (that is the wysiwyg fuction)
then for your php code that send to database, do something like this
$anything = ($_POST['txtEditor']);
$anything you which to use as variable,dont forget the txtEidtor is the form id. with this your wysiwyg is up and working.