Hello dear why i always fail to learning php, would be grateful if someone can help me. :'(
i was followed step by step here :
http://www.w3schools.com/php/php_mysql_insert.asp
but when i click button submit query nothing happen, just show a blank white screen and i dont see new data on database?
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
<?php
$con=mysqli_connect("localhost","root","","garutexpress");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
if data successfull added it should give
echo "1 record added"; but i never see this message.
Your table name is "persons", not "Persons"
When you make a query, your table name has to be the same as in your database. If you look in phpMyAdmin , your table is "persons" with lowercase
Edited according to :
#I Can Has Cheezburger
Please change the name of your table in your code like and make sure about to wrap quotes accordingly :
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql='INSERT INTO persons (Firstname, Lastname, Age)
VALUES
("'.$_POST['firstname'].'","'.$_POST['lastname'].'","'.$_POST['age'].'");
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Common error, you are not wrapping your POST array index with quotes.
Do it like:
$sql='INSERT INTO persons (FirstName, LastName, Age)
VALUES
("'.mysqli_real_escape_string($con,$_POST['firstname']).'","'.mysqli_real_escape_string($con,$_POST['lastname']).'","'.mysqli_real_escape_string($con,$_POST['age']).'");
Also, as #seblaze mentioned, table names are case-sensitive, so use persons instead of Persons
For more security, use prepared statements.
A blank screen means most of the time that you are dealing with some error. You have to turn error reporting on for your local development.
How do I enable error reporting in PHP?
Check that your column names are written camelCase in your script but not in your database.
In most cases it's handy to have an ID column which is your unique identifier.
Good practice: Start using PDO
First,
You need to update the PHP configurations as:
memory_limit = 64M
Make sure you increase the memory .
Then, you need to enable Error reporting, using .htaccess file or configure it with php.ini. Read this for help
After that you can debug your work.
Try the code in this,
http://www.tizag.com/mysqlTutorial/mysqlinsert.php
in w3schools it uses mysqli I also had some issues with it.
in the link it has some sample codes and it uses mysql
Related
I've looked everywhere and I can't find anything helpful. I'm trying to create an online sheep game, and to begin playing the game, the user needs to select the color and name of their first sheep. When submitted, it inserts the data into my MySQL database successfully, but displays this error:
Error: 1
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '1' at line 1
Here's my syntax to connect to the database:
<?php
$conn = mysqli_connect("localhost","root","","flyingfeetranch");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Here's my form and what I use to insert:
<form name="properties" method="POST">
<input type="radio" name="color" value="white" selected="selected">White<br>
Name: <input type="text" name="name" value=" "/>
<input type="submit" name="submitname" value="Submit"/>
</form>
</div>
<?php
if(isset($_POST['submitname']))
{
$Color = $_POST['color'];
$Name = $_POST['name'];
$Age = "12";
$sql = mysqli_query($conn, "INSERT INTO babydolls (name, color, age)VALUES ('$Name', '$Color', '$Age')");
if($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
The "1" stems from querying twice, which means it worked. Had it been a "0", then that'd of been a different ballgame.
Remove one of the querying functions.
Just check with the variable for it.
$sql = mysqli_query($conn, "INSERT INTO babydolls (name, color, age)VALUES ('$Name', '$Color', '$Age')");
if($sql)
{
echo "New record created successfully";
}
Beware, you're open to an sql injection here, use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
Note: You should also check for empty fields and checking if a radio is set should you happen to remove the "selected" from it (bit of a side note here). That could cause you problems if none of those fields are not filled and your db doesn't accept empty/null values.
References:
https://php.net/manual/en/function.empty.php
https://secure.php.net/manual/en/function.isset.php
I installed MySql on my Raspberry Pi 2 Model B+ a few days ago to see if I could use it, PHP, phpmyadmin, and Apache to make an accessible database to organize and catalog books that are around the house. I have a table in a MySQL database set up as a prototype with three columns; Booknumber (set to auto-increment), title, and authorLastName. I'm trying to use a form to insert books into table beta, in database bookProof.
Here's the code for the form:
<html>
<body>
<form action="catalog.php" method="POST">
<p>Book Title: <input type="text" name="title"></p>
<p>Author's Last Name: <input type="text name="authorlastname"></p>
</form>
</body>
</html>
Which links to "catalog.php", which is:
<?php
define('DB_NAME', 'bookProof');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Could not connect: " . $conn->connect_error);
}
$value = $_POST["title"]
$value2 = $_POST["authorlastname"]
$sql = "INSERT INTO beta ('title', 'authorLastName') VALUES ('".$value."', '".$value2."')"
$query = mysqli_query($conn,$sql);
if ($conn->($sql) === TRUE) {
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When demoform.php is opened, it functions normally, but when the "Add Books" button is clicked, it goes to catalog.php as intended, but the catalog.php page is blank, the table is unchanged, and Google Chrome's "Inspect" tool gives the error:
POST http://192.168.254.11/Library/catalog.php 500 (Internal Server Error) catalog.php:1
If anyone knows how to get the input to the database, please let me know.
Note: This is just a home system, so security is not a priority (I don't need SQL code injection protection).
Your note, "...security is not a priority (I don't need SQL code injection protection)" - you might think that, but you should do it anyways. Not only does it protect your database should your system be exposed (or made public at a later time), it will handle strings automatically for you, so that your query won't break if your strings have quotes ' in them.
One issue is that you're using singlequotes around column and table names. This should be backticks, or none at all. Then you were missing a semicolon ; after defining your $value, $value2 and $sql strings.
Then you're doing something a bit odd - which is also causing a parse-error (Had you enabled error-reporting and checked your logs, you'd see a "Parse error: syntax error, unexpected (" error in your logs), you're querying the table with mysqli_query(), but then you try to do it again - except you're trying to query on the querystring, and not the query method. Note the comments I've added in the code below.
// Don't use singlequotes ' for columns and table-names
// Use backticks ` - quotes are for strings
$sql = "INSERT INTO beta (`title`, `authorLastName`) VALUES ('".$value."', '".$value2."')"; // You were also missing a semicolon here!
// $query = mysqli_query($conn,$sql); // Remove this line, as you're attempting to query it twice
if ($conn->query($sql) === TRUE) { // You're missing the query() method here
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Using prepared statements won't be that much of a difference, and you really should do it. There's absolutely no reason to not use prepared statements! Look how little changes that have to be made!
$sql = "INSERT INTO beta (title, authorLastName) VALUES (?, ?)";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("ss", $value, $value2);
$stmt->execute();
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You've also got some invalid HTML which would cause issues - the following line had a missing quote to close off the type attribute.
<input type="text" name="authorlastname">
I suggest you read the following documentation and articles
When to use single quotes, double quotes, and backticks in MySQL
How can I prevent SQL injection in PHP?
PHP manual on mysqli_stmt::bind_param
How to get useful error messages in PHP?
PHP Parse/Syntax Errors; and How to solve them?
As a final note, you should check that the form was submitted and that it has values before inserting into the database. Also, using variable-names like $value and $value2 are not really descriptive - you should avoid it and use proper names for your variables.
I'm making a small project and I'm having some trouble with a php script. Basically, when they enter the text then click 'Enter' It loads to the 'insert.php'. The thing is, if they just visit the insert.php page without going to the main page It enters a plan table which could cause big problems.
Code:
$con=mysqli_connect("localhost","info","info","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
Can you help me fix this problem as It could cause a lot of troubles.
First you need to validate your $_POST variables by using isset().
If they are not submitted from a form, $_POST will be empty. Meaning that when a user try to type in the url, there won't be any post data and your SQL queries won't run.
2nd, you are subject to SQL injection since you are not escaping the content.
I'd suggest escaping each variable by using a prepared statement or mysqli_real_escape_string (less secure but better than nothing).`
if ( isset($_POST) && !empty($_POST['firstname']) && !empty($_POST['lastname']) && !empty($_POST['age'])) {
$con=mysqli_connect("localhost","info","info","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//simple example of escaping variables - BUT NOT AS SECURE AS PREPARED STATEMENT!!
$firstname = $con->real_escape_string($_POST['firstname']);
$lastname = $con->real_escape_string($_POST['lastname']);
$age = $con->real_escape_string($_POST['age']);
//With MySQLi it is best practice to use `prepere`, `bind_param` and `execute:
//or use PDO.
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$firstname','$lastname','$age')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
}
Lastly, you were missing the single quotes inside your $_POST variables.
Hope this helps!
This is pretty simple.
if(isset($_POST)):
//all of your code here
endif;
You have to check if $_POST exists to trigger your sql request
if (isset($_POST)){
//script
}
One of the first things that I see right off the top of my head is the fact that you are not checking to ensure that something has infact been typed Into your input box that passes the data to your other file. You can try to use isset() or array_key_exist(). Not to mention these are things that you should be doing anyway.
I would like a user to be able to insert a "bid" into a MySQL table using a php form - this is only for demo, not live purpose. I get the following error message,
Error: 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 ''90','2011-07-13'' at line 3 (Line 3 refers to my tag?) I figure it doesnt like the form inputs just being "text" type, but no idea how to fix it - all advice very welcome, this is my form & php code below;
<form action="insert.php" method="post">
<div><label for="commodity">Commodity</label><input type="text" name="commodity"/></div>
<div><label for="region">Region</label><input type="text" name="region"/></div>
<div><label for="member">Member</label><input type="text" name="member" /></div>
<div><label for="size">Size</label><input type="int" name="size" /></div>
<div><label for="price">Post Bid</label><input type="decimal" name="price" /></div>
<div><label for="posted">Date Posted</label><input type="text" name="posted"/></div>
<P><label for="submit">Submit Bid</label><input type="submit" /></P>
</form>
& php
<?php
$con = mysql_connect("localhost","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("palegall_newTrader", $con);
$sql="INSERT INTO `buy` (commodity, region, member, size, price, posted)
VALUES
('$_POST[commodity]','$_POST[region]','$_POST[member]','$_POST[size]','$_POST[price]','$_POST[posted]'";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Many thanks in advance, scotia
You're vulnerable to SQL injection, and your POST probably contains a ', which is causing the syntax error. Try the following:
$commodity = mysql_real_escape_string($_POST['commodity']);
$region = mysql_real_escape_string($_POST['region']);
etc...
$sql = "INSERT INTO ... VALUES ('$commodity', '$region', etc...)";
the escape function will ensure that any SQL metacharacters in the data are escaped, so they can't "break" your query. Never EVER directly insert user-provided data into an SQL query, even if it's a simple script that only you will ever use. Get into the habit of escaping everything (or better yet, using PDO prepared statements), because at some point, you'll get burned if you don't.
Your closing parenthesis need to go after the last value to be inserted, now it's after the 4th element. Put it at the and of the statement.
$sql="INSERT INTO `buy` (commodity, region, member, size, price, posted)
VALUES
('$_POST[commodity]','$_POST[region]','$_POST[member]','$_POST[size]','$_POST[price]','$_POST[posted]')"
Also, follow #Marc's advice and sanatize your input.
Shouldn't it be
$sql="INSERT INTO `buy` (commodity, region, member, size, price, posted) VALUES ('$_POST[commodity]','$_POST[region]','$_POST[member]','$_POST[size]','$_POST[price]','$_POST[posted]')";
There is a misplaced parenthesis after $_POST['size'] that should be after $_POST[posted]
The SQL should look like this:
$sql="INSERT INTO `buy` (commodity, region, member, size, price, posted)
VALUES
('$_POST[commodity]','$_POST[region]','$_POST[member]','$_POST[size]','$_POST[price]','$_POST[posted]')";
I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database. I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.
Here's the latest version of the code. Could someone please tell me what I am doing wrong?
* Basic HTML Form *
<form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>
<p>Metric1<br />
<input name="metric1" type="text" /></p>
<p>Metric2<br />
<input name="metric2" type="text" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
* Processor File *
<?php
$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];
$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
{die('Could not connect to database: ' . mysql_error());}
mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
Print "Your metrics have been successfully added to the database.";
mysql_close($con);
?>
Your mysql-syntax is wrong.
Try
INSERT INTO my_metrics
SET
date = '$date',
metric1 = '$metric1',
metric2 = '$metric2'
Depending on what the table looks like, your code may or may not work,
"INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')"
assumes that the fields are in that order, and that there are no fields before this one.
"INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')"
would be more future proof, and may also solve your problem as they are going to insert into the correct fields.
It is also possible that you are getting some bad data for the field definitions, try doing the insert in phpmyadmin or at the command line instead of in php, then work backwards from there.
As far as the vulnerability to SQL injection, you should feed your input strings to mysql_real_escape_string();. This will escape any unwanted characters.
When connecting to the database, you write
$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
You can simplify this, and making this more readable by writing
mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql:<hr>'.mysql_error());
For solving your problem, see if specifieng column names helps. If you don't, mysql will assume you enter values in the order of the columns, you might get some trouble with an ID field, or something like that. Your query could look like this:
"INSERT INTO my metrics (date,metric1,metric2) VALUES ('$data','$metric1','$metric2'))"
And finally, here's a speed concideration.
There are two ways to write strings: using single quotes ('string'), and using double quotes ("string"). in the case of 'string' and "string", they will work exactly the same, but there is a difference. Look at the following code
$age=3
echo 'the cat is $age years old.';
//prints out 'the cat is $age years old.'
echo "the cat is $age years old.";
//prints out 'the cat is 3 years old'
echo 'the cat is '.$age.' years old';
//prints out 'the cat is 3 years old'.
As you can see from this example, when you use single quotes, PHP doesn't check the string for variables and other things to parse inside the string. Doing that takes PHP longer than concatinating the variable to the string. so although
echo "the cat is $age years old"
is shorter to type than
echo 'the cat is '.$age.' years old';
it will boost your page loading when you write larger applications.
Hooray! Hooray! Hooray!
Thank you all for such helpful advice! It finally works! Here's the updated code in case any other newbies have the same issue. (Hope I didn't screw anything else up.)
Form
<form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>
<p>Metric1<br />
<input name="metric1" type="text" /></p>
<p>Metric2<br />
<input name="metric2" type="text" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
Processor
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
// 1. Create connection to database
mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql: <hr>'.mysql_error());
// 2. Select database
mysql_select_db("my_metrics") or die('Could not connect to database:<hr>'.mysql_error());
// 3. Assign variables (after connection as required by escape string)
$date=mysql_real_escape_string($_POST['date']);
$metric1=mysql_real_escape_string($_POST['metric1']);
$metric2=mysql_real_escape_string($_POST['metric2']);
// 4. Insert data into table
mysql_query("INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')");
Echo 'Your information has been successfully added to the database.';
print_r($_POST);
mysql_close()
?>
Here you go love :) try W3c it a good place for new pepps
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO my_metrics (date, metric1, metric2)
VALUES
('$_POST[date]','$_POST[mertric1]','$_POST[metric2]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Your metrics have been successfully added to the database.";
mysql_close($con)
?>