PHP not saving data to database - php

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.

Related

PHP $_POST data not being passed between pages

I've been trying to make a simple html form that passes data to a php page, eventually for insertion into a sql database. I've made forms successfully for but for some reason can't find what the data isn't getting passed in this instance.
Using var_dump($_POST), I see upon submission of the html form there is no data being transferred. I have tried var_dump both within and outside of a if(isset($_POST['submit'])) {}, both with no success. I'm beginning to think it's possibly an issue with my php install or something along those lines?
HTML FORM:
<form action="programinsert.php" method="POST">
<p>
<label for="program_title"> Program Title: </label>
<input name="program_title" type="text" id="program_title">
</p>
<input type="submit" value="Submit">
</form>
programinsert.php:
<?php
session_start();
define('DB_NAME', 'rluh_website');
define('DB_USER', 'root');
define('DB_PASS', 'swang');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
if(!$link) {
die('Error: ' . mysqli_error($link));
}
$db_select = mysqli_select_db($link, DB_NAME);
if(!$db_select) {
die('Cannot use ' . DB_NAME . ': ' . mysqli_error($link));
}
var_dump($_POST);
?>
Thanks for the replies everyone. The issue in the end seemed to be when running the web pages (which are hosted locally) from the IDE I am using, PhpStorm. PhpStorm opens up the pages under localhost:63342, rather than plain localhost. Erasing these numbers let the data pass through as expected.
I believe you need to GET what is being posted by the form.
Here is a simplified plunk of the issue:
https://embed.plnkr.co/uLnaPnHFtrmE6Dr6101F/
Are you sure database information is correct ? And try adding a "/"

Connect a particular MySQL Database according to an html form

What i want to do is to connect to a particular Database according to the value of an html form, first of all is it possible ?
I have got some code to propose :
This is my form in the previous page :
<form method="post" action="connexion.php">
<li> <strong><b>Aircraft</b></strong> : <input type="text" name="Aircraft" placeholder="MRJ" /><br /> </li>
<li> <strong><b>Systeme</b></strong> : <input type="text" name="Systeme" placeholder="ATAXX" /><br /> </li>
<li> <strong><b>Projet</b></strong> : <input type="text" name="Projet" placeholder="CMA" /><br /> </li>
<br />
<input type="submit" value="Submit">
And my code for the connexion.php :
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '#Rugby3390');
define('DB_NAME', 'ata."$Systeme"');
/* Attempt to connect to MySQL database */
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
header("location: ../FailureCondition/failurecondition$_POST[Systeme].php");
?>
So if you could understand me, according to data entered in Systeme, i would like to connect to a special database named ata(user input) and redirect to a page whit also the information of the user input named failurecondition(user).php
What s wrong in my code ?
Thx
While Nirav and Arkits' solution should solve the problem, it strikes me as fundamentally wrong to define a constant from a variable. I suggest that this is more correct:
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD,$_POST['Systeme']);
Further, as is the case here, where your application has multiple databases, using an implicit database in queries is likely to cause pain later. If the seperation of databases is merely an organizational concern, then a better approach would be to explicitly reference the database in the queries:
$activeDB=$_POST['Systeme'];
$sql="SELECT * FROM ${activeDB}.atable";
OTOH if it is intended as a means of providing scalability, then your code does not address this - and you should be using something like:
$dbs=array(
'db1'=>array(
'user'=>'mysqluser', 'host'=>'localhost', 'password'=>'s3cr3t'
),
'db2'=>array(
'user'=>'mysqluser', 'host'=>'localhost', 'password'=>'s3cr3t'
),
'db3'=>array(
'user'=>'other', 'host'=>'192.168.22.4', 'password'=>'swordfish'
)
...
);
$use=$dbs[$_POST['Systeme']];
if (!is_array($use)) {
...
}
$mysqli = new mysqli($use['host'], $use['user'], $use['password'], $_POST['Systeme']);
Close the form tag (</form>) in your html page if not already. And try this:
define('DB_NAME', 'ata'.$_POST['Systeme']);

Cannot INSERT data into mysql using php

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]."')

How do I complete this login script?

I've almost completed my login script, but I don't know how to check if the username & password is correct.
Here's my script files.
index.php:
<html>
<body>
<form action="action1.php" method="post">
Username: <input type="text" name="uname">
Password: <input type="password" name="pword">
<input type="submit">
</form>
</body>
</html>
The index.php file is just the page that I use to collect the info from my users for registration.
action1.php:
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die ('Could not connect: ' . mysql_error());
}
mysql_select_db("user1", $con);
$sql="INSERT INTO useri1 (uname, pword)
VALUES
('$_POST[uname]','$_POST[pword]')";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
The action1.php file is just the page that registers the users into the database.
login.php:
<html>
<body>
<form action="checklogin.php" method="post">
Username: <input type="text" name="uname1">
Password: <input type="password" name="pword1">
<input type="submit">
</form>
</body>
</html>
The login.php file is just the page I use for the users to type their login info in.
Now this is my problem, I have no idea of how to check the users login info so they can proceed to the members only area. I'm a newbie & any help is GREATLY appreciated.
Thanks,
--Devin
Firstly you want to use mysqli instead of mysql, because mysql is outdated and no longer actively developed. Secondly you want to start escaping your database queries to stop sql injection. In the code below, I used a session to keep track of the user. You can learn more about sessions here.
<?php
session_start();
$mysqli = new mysqli('localhost', 'root', DB_PASSWORD, 'user1');
/* check connection */
if ($mysqli->connect_error)
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
/* escape string from sql injection */
$userName = $mysqli->real_escape_string($_POST['uname1']);
/* query database */
$result = $mysqli->query("SELECT `pword` FROM `user1` WHERE `uname` = '".$userName."'");
if ($result->num_rows == 1) {
while ($col = $result->fetch_array(MYSQLI_ASSOC)) {
// This presumes you're storing your passwords in plain text.
// If you hashed your passwords or anything, you would have to do the same to $_POST['pword']
if ($_POST['pword'] == $col['pword']) {
// You could do anything here, but sessions are a way of keeping track of a user.
$_SESSION['userName'] = $_POST['uname1'];
$_SESSION['loggedIn'] = true;
}
}
}
$result->close();
/* don't forget to close the connection */
$mysqli->close();
?>
You would run a query along the lines of this:
$user_check_query = "SELECT * FROM useri1 WHERE uname=" . $_POST['uname'] . " AND pword=" . $_POST['pword'] .";";
And if the query returns a value, then they can proceed. If the query returns nothing, they cannot pass. As for the logic, look at the code you have created and see how to create if and else statements to handle the logic.
You need to do a SELECT query - something along the lines of
SELECT STRCMP('{$_POST['pword']}', pword) FROM useri1 WHERE uname = '{$_POST['uname']}'
This should return a value in the range [-1, 1] - if it is not 0, the password is wrong. If there is no rows, the user does not exist.
You need to think about SQL injections as well - but that could very well be an exercise for another day.

PHP form not writing to mySQL database

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)
?>

Categories