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)
?>
Related
I am creating a users database where there are 4 fields: ID, username, password, and occupation. This is a test database. I tried querying the db table and it worked but i have a lot of trouble having a user input and a MySQL query based off of it. I run an Apache server in Linux (Debian, Ubuntu).
I have 2 pages. The first one is a bare-bone test index page. this is where there are textboxes for people to input easy info to register their info in the db. Here is the code for it:
<html>
<form action="reg.php" method="POST">
Username:
<input type="text" name="u">Password:
<input type="password" name="p">Occupation:
<input type="text" name="o">
<input type="submit" value="register">
</form>
</html>
After the submit button is clicked. It goes to the reg.php file. This is where it gets complicated. The page goes blank!!! Nothing is displayed or inputted in the db. Normal queries work well, but when user interaction is added, something is wrong. Here is the code for reg.php:
<?php
$un = $_POST["u"]
$pk = $_POST["p"]
$ok = $_POST["o"]
$u = mysql_real_escape_string($un);
$p = mysql_real_escape_string($pk);
$o = mysql_real_escape_string($ok);
$link = mysql_connect('localhost', 'root', 'randompassword');
if (!$link){
die(' Oops. We Have A Problem Here: ' . mysql_error());
}
if ($link){
echo 'connected succesfully';
}
mysql_select_db("forum") or die(' Oops. We Have A Problem Here: ' . mysql_error());
$data = mysql_query("INSERT INTO users (username, password, occupation) VALUES ('{$u}', '{$p}', '{$o}')");
?>
Can anyone hep me to correct this code to make this work?
Thank you so much for your time. Much appreciated.
EDIT:
I noticed that i did not add semicolons in the first 3 lines. after doing so i got this 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 '{'', '', '')' at line 1." Can someone explain why?
EDIT: the website is just on my local machine...
on an apache server on linux
You are missing semi-colons in the first three lines.
$un = $_POST["u"];
$pk = $_POST["p"];
$ok = $_POST["o"];
mysql_real_escape_string() requires a db connection.
Try this ....
<?php
$un = $_POST["u"];
$pk = $_POST["p"];
$ok = $_POST["o"];
$link = mysql_connect('localhost', 'root', 'randompassword');
if (!$link){
die(' Oops. We Have A Problem Here: ' . mysql_error());
}
if ($link){
echo 'connected succesfully';
}
mysql_select_db("forum") or die(' Oops. We Have A Problem Here: ' . mysql_error());
$u = mysql_real_escape_string($un);
$p = mysql_real_escape_string($pk);
$o = mysql_real_escape_string($ok);
$sql = "INSERT INTO users (username, password, occupation) VALUES ('$u', '$p', '$o')";
$ins_sql = mysql_query($sql);
IF($ins_sql) {
echo 'Inserted new record.';
}ELSE{
echo 'Insert Failed.';
}
?>
Try adding this to the top of your script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
This way you will see all errors that you made syntactically or even within your SQL.
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
I feel like I'm getting closer to figuring out why PHP is not saving data to my database.
I've tried learning PHP and MySQL from numerous tutorials and all have failed me.
So... I feel like there may be something that I haven't been specifying when trying to connect to a MySQL database.
In a recent tutorial that simply outputs text from an input to a table in MySQL, I got an Error stating that the server "localhost" was not found.
My Apache has been installed on port 60 (not the default port 80). So I figured that that might be the problem. I tried adding localhost:60 to the mysqli_connect rather than localhost itself and the error disappeared!
There is still a problem though: 1. It takes forever to load the demo.php page (see code below). 2. The data still isn't being added....
Here is the code (I converted it from the original MySQL on the video, to MySQLi and added comments):
demo.php:
<?php
define('DB_NAME', 'forms1');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost:60');
// stored in a variable to TEST if it's working
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_HOST);
// TEST if a link has been established (connection)
if (!$link) {
die('Could not connect:' . mysqli_error($link));
}
// same as above
$db_selected = mysqli_select_db($link,DB_NAME);
if(!$db_selected) {
die('Can\t use ' . DB_NAME . ': ' . mysqli_error($link));
}
// Check SUCCESS with commented command below
// echo 'Connected successfully.';
// stored in a variable to shorten
$value = $_POST['input1'];
// stored in a variable to TEST
$sql = "INSERT INTO demo (input1) VALUES ('$value')";
if(!mysqli_query($link, $sql)) {
die('Error: ' . mysqli_error($link));
}
mysqli_close($link);
?>
demo-form.php:
<form action="demo.php" method="post" />
<p>Input 1: <input type="text" name="input1" /></p>
<input type="submit" value="Submit" />
</form>
I've also had the same problem with another code, see the thread here:
PHP database won't save data
I really hope that someone can help me here.
It's a shame that I haven't even gotten the basis to work yet...
Thanks!
Try this out: (your present code did not work for me) HTML form and PHP/SQL are all-in-one.
<?php
DEFINE ('DB_USER', 'xxx');
DEFINE ('DB_PASSWORD', 'xxx');
DEFINE ('DB_HOST', 'xxx');
DEFINE ('DB_NAME', 'xxx');
$link = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("could not connect");
if(isset($_POST['submit'])){
// stored in a variable to shorten
$value = mysqli_real_escape_string($link,$_POST['input1']);
// stored in a variable to TEST
$sql = "INSERT INTO demo (input1) VALUES ('$value')";
if(!mysqli_query($link, $sql)) {
die('Error: ' . mysqli_error($link));
}
else { echo "Success"; }
} // if(isset($_POST['submit']))
mysqli_close($link);
?>
<form action="" method="post" />
<p>Input 1: <input type="text" name="input1" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
MySQL used port 3306 as the default. Does PHP connect directly to the database? If yes, try making your port match.
Did you add permissions to MySQL to allow your app to connect and interact with the database? You should read about GRANT and permissions.
But the comment by Dagon above is a serious one: exposting a database directly to the Internet should only be done if you're willing to have the data stolen, trashed, or both.
I'm using a simple html-form and PHP to insert Strings into mySQL Database, which works fine for short strings, not for long ones indeed.
Using the phpmyadmin I'm able to insert Strings of all lengths, it's only doesn't work with the html file and PHP.
Will appreciate every kind of help, would love to learn more about this topic...
Thank you all a lot in advance and sorry if the question is to simple...
There are two very similar questions, I found so far... unfortunately they couldn't help:
INSERTing very long string in an SQL query - ERROR
How to insert long text in Mysql database ("Text" Datatype) using PHP
Here you can find my html-form:
<html>
<body>
<form name="input" action = "uploadDataANDGetID.php" method="post">
What is your Name? <input type="text" name="Name"><br>
Special about you? <input type="text" name="ThatsMe"><br>
<input type ="submit" value="Und ab die Post!">
</form>
</body>
</html>
and here is the PHP-Script named uploadDataANDGetID.php :
<?php
$name = $_POST["Name"];
$text = $_POST["ThatsMe"];
$con = mysql_connect("localhost", "username", "password") or die("No connection established.");
mysql_select_db("db_name") or die("Database wasn't found");
$q_post = mysql_query("INSERT INTO profiles VALUES (null, '{$name}' ,'{$text}')");
$q_getID =mysql_query("SELECT ID FROM profiles WHERE Name = '{$name}' AND ThatsMe = '{$text}'");
if(!$q_post) // if INSERT wasn't successful...
{
print('[{"ID": "-3"}]');
print("uploadDataAndGetID: Insert wasn't successful...");
print("about ME: ".$text);
}
else // insertion succeeded
{
while ($e=mysql_fetch_assoc($q_getID))
$output[]=$e;
//checking whether SELECTion succeeded too...
$num_results = mysql_num_rows($q_getID);
if($num_results < 1)
{
// no such profile available
print('[{"ID": "-1"}]');
}
else
{
print(json_encode($output));
}
}
mysql_close();
?>
Thank you guys!
Use the newer way to connect to MySQL and use prepared statements http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
you MUST escape your strings, with mysql_real_escape_string, like this:
$name = mysql_real_escape_string($_POST['Name']);
$text = mysql_real_escape_string($_POST["ThatsMe"]);
$q_post = mysql_query('INSERT INTO profiles VALUES (null, "' . $name . '" ,"' . $text . '")');
also read about SQL injection
I have been trying for two days now to figure this one out. I copied verbatim from a tutorial and I still cant insert data into a table. here is my code with form
<font face="Verdana" size="2">
<form method="post" action="Manage_cust.php" >
Customer Name
<font face="Verdana">
<input type="text" name="Company" size="50"></font>
<br>
Customer Type
<font face="Verdana">
<select name="custType" size="1">
<option>Non-Contract</option>
<option>Contract</option>
</select></font>
<br>
Contract Hours
<font face="Verdana">
<input type="text" name="contractHours" value="0"></font>
<br>
<font face="Verdana">
<input type="submit" name="dothis" value="Add Customer"></font>
</form>
</font>
<font face="Verdana" size="2">
<?php
if (isset($_POST['dothis'])) {
$con = mysql_connect ("localhost","root","password");
if (!$con){
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES
('$_POST[Company]','$_POST[custType]','$_POST[contractHours]')";
mysql_query($sql, $con);
print_r($sql);
mysql_close($con);
}
?>
This is my PHPmyadmin server info:
Server: 127.0.0.1 via TCP/IP
Software: MySQL
Software version: 5.5.27 - MySQL Community Server (GPL)
Protocol version: 10
User: root#localhost
Server charset: UTF-8 Unicode (utf8)
PLEASE tell me why this wont work. when I run the site it puts the info in and it disappears when I push the submit button, but it does not go into the table. There are no error messages that show up. HELP
I have improved a little bit in your SQL statement, stored it in an array and this is to make sure your post data are really set, else it will throw a null value. Please always sanitize your input.
in your Manage_cust.php:
<?php
if (isset($_POST['dothis']))
{
$con = mysql_connect ("localhost","root","password");
if (!$con)
{
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$company = isset($_POST['Company'])?$_POST['Company']:NULL;
$custype = isset($_POST['custType'])?$_POST['custType']:NULL;
$hours = isset($_POST['contractHours'])?$_POST['contractHours']:NULL;
$sql = "INSERT INTO cust_profile(Customer_Name,
Customer_Type,
Contract_Hours)
VALUES('$company',
'$custype',
'$hours')
";
mysql_query($sql, $con);
mysql_close($con);
}
?>
First of all, don't use font tags...ever
Secondly, because of this line:
if (isset($_POST['dothis'])) {
It looks like your HTML and PHP are combined into one script? In which case, you'll need to change the action on the form to something like this:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
Plus, you can kill a bad connection in one line:
$con = mysql_connect("localhost","root","password") or die("I died, sorry." . mysql_error() );
Check your posts with isset() and then assign values to variables.
var $company;
if(isset($_POST['Company']) {
$company = $_POST['Company'];
} else {
$company = null;
}
//so on and so forth for the other fields
Or use ternary operators
Also, using the original mysql PHP API is usually a bad choice. It's even mentioned in the PHP manual for the API
Always better to go with mysqli or PDO so let's convert that:
//your connection
$conn = mysqli_connect("localhost","username","password","averyit_net");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours)
VALUES ($company,$custType,$contractHours)";
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Assuming you set these
$stmt = mysqli_prepare($conn, $sql);
$stmt->execute();
$stmt->close();
Someone tell me if this is wrong, so I can correct it. I haven't used mysqli in a while.
Change the $sql to this:
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES ('".$_POST[Company]."','".$_POST[custType]."','".$_POST[contractHours]."')