PHP $_POST data not being passed between pages - php

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 "/"

Related

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']);

linking and sending form values to mysql database?

My html code:
<form action="send_post.php" method="post">
<input type="submit" value="Login" />
</form>
PHP code:
<?php
$con = mysqli_connect("","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
// echo('Connected with Mysql');
}
#mysql_select_db("a", $con);// connect to database db_name
if (isset($_POST['Submit']))
{
$email=$_POST['email'];
$pass=$_POST['pass'];
$sql_query="INSERT INTO formdata (email, pass) VALUES('$email', '$pass')";}
?>
Database name: mysql
Table name: formdata
Why it is not working? in second line I used 'local host' first but I was receiving error so I removed it.
You use the mysqli_ API to connect to your database and then test for errors and try to select a database with the mysql_ API. Pick one and stick to it. (Don't pick mysql_ it is deprecated).
You only run the form handling code if there is a Submit data item in the submitted data. You have no form control with name="Submit" so that will never happen.
Your form handling code expects there to be email and pass data in the submitted data but your form does not have fields with those names.
Constructing an SQL query as a string and storing it in a variable is insufficient to do anything to your database. You have to actually sent it to the database server. That would use mysqli_query with your current approach, but you should switch to prepared statements

PHP not saving data to database

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.

Error 500 when submitting PHP form to database

I have created an SQL database using ProgreSQL with Heroku for my Facebook web app, the following code is the form to collect the data
</style>
<div class="container">
<form action="insert.php" method="post" onSubmit="window.location.reload()">
Cover URL: <input type="text" name="Cover URL" id="coverURL"><br><br>
Title: <input type="text" name="Title" id="title"><br><br>
Author: <input type="text" name="Author" id="author"><br><br>
Genre:<br> <select name="genre" id="genre">
<option>Adventure & Action</option>
<option>Anthologies</option>
<option>Classics</option>
<option>Sport</option>
<option>War</option>
//More options in actual code, just deleted some to save space.
</select><br><br>
Total Pages: <input type="number" name="TotalPages" id="totalpages"><br><br>
Curent Page: <input type="number" name="CurrentPage" id="currentpage"><br><br>
<input type="submit"> </form><br><br></div>
</center>
</section>
That then calls insert.php
<?php
$dbconn = pg_connect("host=ec2-54-243-190-226.compute-1.amazonaws.com port=5432 dbname=d6fh4g6l0l6gvb user=[REMOVED] password=[REMOVED] sslmode=require options='--client_encoding=UTF8'")
or die('Could not connect: ' . pg_last_error());
pg_query("INSERT INTO books(coverURL, title, author, genre, currentPg, totalPg) VALUES('"$_POST["coverURL"]"','"$_POST["title"]"','"$_POST["author"]"','"$_POST["genre"]"', '"$_POST["currentpages"]"','"$_POST["totalpages"]"')");
pg_close($dbconn);
?>
The problem is I get error 500 when I hit submit, after looking around online most solutions say there must be an error in the PHP, but due to my inexperience (learning this as I go) I have no idea what I've done wrong.
I can provide more information if necessary. Thanks in advance!
Try this:
Please make sure the names of the html inputs match the $_POST values.
mysqli_query($con,"INSERT INTO books(coverURL, title, author, genre, currentPg, totalPg) VALUES('".$_POST["coverURL"]."','".$_POST["title"]."','".$_POST["author"]."','".$_POST["genre"]."','".$_POST["currentpages"]."','".$_POST["totalpages"]."')");
EDIT: use this statement ------^
And instead of:
'$_POST[author]'
It is better to do them like this:
'".$_POST["author"]."'
And also are you aware that $sql isnt actually being inserted into the db?
An error 500 is a "internal server error". This basically means that something on the server side has failed, it's just a very generic error message. Basically it can be everything, it's not only limited to your script. It could be a Apache module error or anything else that refuses your WebServer software to handle the request without any fatal failures.
If it only occurs on the same actions (like submitting a form or calling a special page) it's very likely it's a script error causing the error 500.
You should look up your log files, esp. the apache error log. It should contain further informations on what has gone wrong.
In your case, maybe your sever is not allowed to connect to an external database server, but it's only a guess.
The problem is that you're really "mixing" things together. Your code connects with pg_connect and querying with mysqli. Use only Postgree functions to connect to the database Read manual at http://www.php.net/manual/en/ref.pgsql.php.
I would do something like: (I have not tested it though)
<?php
$dbconn = pg_connect("host=ec2-54-243-190-226.compute-1.amazonaws.com port=5432 dbname=d6fh4g6l0l6gvb user=[REMOVED] password=[REMOVED] sslmode=require options='--client_encoding=UTF8'") or die('Could not connect: ' . pg_last_error());;
$coverUrl = $_POST["coverURL"];
$title = $_POST["title"];
$author = $_POST["author"];
$genre = $_POST["genre"];
$currentPages = $_POST["currentpages"];
$totalPages = $_POST["totalpages"];
pg_query_params($dbconn, "INSERT INTO books(coverURL, title, author, genre, currentPg, totalPg) VALUES($1,$2,$3,$4,$5,$6)", array($coverUrl, $title, $author, $genre, $currentPages, $totalPages));
pg_close($dbconn);
?>

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