if(isset($_POST['submit'])){ } NOT WORKING on submit button - php

I have a problem where when ever I load my page it says that the form is done even when I don't press submit here is the code -
<?php
$db_host = 'localhost';
$db_name = 'info';enter code here
$db_user = 'root';
$db_password = '';
try {
$db = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name, $db_user, $db_password);
echo "connected<br><br>";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
die();
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$info = $_POST['info'];
$date = $_POST['date'];
$sql = "INSERT INTO info (name, phone, email, info, date)";
$sql .= " VALUES (:name, :phone, :email, :info, :date)";
$query = $db->prepare($sql);
$query->execute(array(
':name' => $name,
':phone' => $phone,
':email' => $email,
':info' => $info,
':date' => $date
));
echo "done<br>";
}
?>

Add a check so it checks or something is posted:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
//You code
}
I hope this will help.

Just use one && condition along with your isset
Lets just say, if this is your submit button
<input type="submit" value="SomeValue" name="SomeName">
Then you simply use this as your if condition to check if your button with name "SomeName" has actually been pressed.
if(isset($_POST['SomeName']) && $_POST['SomeName']=='SomeValue')
{
//Rest of your code
}
This If implies, your submit button has been pressed it after checking its value. Hope it helps.

Related

PHP fails at inserting values into database

I'm using a WordPress theme for my site, but customizing it has given me such a headache that we are trying to use our own hand written from instead of the one provided by WordPress.
I have written a php-script that should insert values from this form into a custom table in a custom database outside of the wordpress database. How ever when I try to run it I get no error messages, and no data is inserted into the database.
my PHP code, please not that I have changed the $user and $pass to not show here. I've tested the login info used in this script via terminal on my database, and it worked fine. See the full file here page.sign.php
if(isset($_POST['submit'])) {
$lastname = $_POST["lname"];
$firstname = $_POST["fname"];
$email = $_POST["email"];
$affiliation = $_POST["affiliation"];
$country = $_POST["X"];
$position = $_POST["position"];
$hindex = $_POST["scholar"];
$gender = $_POST["optionsRadios"];
$city = $_POST["city"];
$webpage = $_POST["webpage"];
$newsletter = $_POST["newsletter"];
//Source https://gist.github.com/adrian-enspired/385c6830ba2932bc36a2
$host = "localhost";
$dbname = "petition";
$user = "<username>";
$pass = "<password>";
$charset = "UTF8MB4"; // if your db does not use CHARSET=UTF8MB4, you should probably be fixing that
$dsn = "mysql:host={$host};dbname={$dbname};charset={$charset}";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
echo "<h1>Error connecting to the database </h1>";
}
$stmt = $pdo->prepare("INSERT INTO petitioners (lastname, firstname, email, affiliation, country, position, hindex, gender, city, webpage, newsletter)
VALUES
(:lastname, :firstname, :email, :affiliation, :country, :position, :hindex, :gender, :city, :webpage, :newsletter)");
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':firstname', $firsname);
$stmt->bindParam(':email',$email);
$stmt->bindParam(':affliation',$affiliation);
$stmt->bindParam(':country',$country);
$stmt->bindParam(':position',$position);
$stmt->bindParam(':hindex',$hindex);
$stmt->bindParam(':gender',$gender);
$stmt->bindParam(':city',$city);
$stmt->bindParam(':webpage',$webpage);
$stmt->bindParam(':newsletter',$newsletter);
$stmt->execute();
echo "<h1>Signatory succefully registered</h1>";
$stmt->close();
$conn->close();
}

Simple PHP Form SQL Insert

I need some help with a very basic issue that I cannot resolve.
A bit of background: I have a PHP form and I would like the information inside the table to insert into my SQL table. For some reason, when I hit submit nothing inserts into the table and I have no idea why. Please help!
This is the PHP Code:
<?php
try
{
$db = new PDO('mysql:host=' . $Database_Host . ';dbname=' . $Database_Database, $Database_Username, $Database_Password);
}catch(PDOException $e){
die("Failed to connect to database! Please check the database settings.");
}
if(isset($_POST['submit'])) {
$result = mysql_query('INSERT INTO requests (song,name,dedicated,time) VALUES ("' . mysql_real_escape_string($_POST['name']) . '", "' . mysql_real_escape_string($_POST['dedicated']) . '", "' . mysql_real_escape_string($_POST['song']) . '", UNIX_TIMESTAMP())');
if ($result) {
echo 'Song requested successfully!<br />';
}
}
?>
This is the HTML Code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">Request:<br /><br />
Song:<br />
<input type="text" name="song"><br />
Name:<br />
<input type="text" name="name"><br />
Comments:<br />
<input type="text" name="dedicated"><br />
<input type="submit" name="submit" value="Submit" >
</form>
What this is meant to do is insert the request form into the SQL table, however nothing is happening. Any help is appreciated.
Kind Regards,
Edward
You can't mix mysql and PDO like that. You should use a PDO prepared query for the insert.
Also, the order of the values in the VALUES list have to match the column list -- you had the values in the order name, dedicated, song, time instead of song, name, dedicated, time.
<?php
if (isset($_POST['submit'])) {
try
{
$db = new PDO('mysql:host=' . $Database_Host . ';dbname=' . $Database_Database, $Database_Username, $Database_Password);
}catch(PDOException $e){
die("Failed to connect to database! Please check the database settings.");
}
$stmt = $db->prepare('INSERT INTO requests (song,name,dedicated,time) VALUES (:song, :name, :dedicated, UNIX_TIMESTAMP())');
$result = $stmt->execute(array(':song' => $_POST['song'], ':name' => $_POST['name'], ':dedicated' => $_POST['dedicated']));
if ($stmt->rowCount == 1) {
echo "Song requested successfully";
} else {
echo "Song could not be requested";
}
}
You should study about pdo and mysql and then use them ...
just see this simple example with mysql :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
and this one with pdo :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
// insert another row
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
// insert another row
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
I prefer using pdo
Source : http://www.w3schools.com/php/php_mysql_prepared_statements.asp
NOTE : use prepared statements to avoid sql injection .

Can't insert data via PDO using associative array

That's how I'm trying to do it:
database.php:
<?php
$host = "host";
$user = "user";
$pass = "password";
$dbname = "database";
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
file that must insert data:
<?php
include 'database.php';
$_POST['name'] = 'test';
$_POST['message'] = 'test';
$_POST['date'] = 'test';
var_dump($_POST);
if(isset($_POST['name']) && isset($_POST['message'])){
$data = array(
'name' => $_POST['name'],
'shout' => $_POST['message'],
'date' => $_POST['date']
);
$STH->bindParam(':name', $_POST['name']);
$STH->bindParam(':message', $_POST['message']);
$STH->bindParam(':date', $_POST['date']);
try {
$STH = $DBH->prepare("INSERT INTO shouts (name, message, date) value (:name, :message, :date)");
$STH->execute($data);
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
According to this http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059 it should accept associative array. But instead it does nothing and says that I have an error in this line:
$STH = $DBH->("INSERT INTO shouts (name, message, date) value (:name, :message, :date)");
What can be causing it, and how I can actually use an associative array to insert data into MySQL database using PDO?
Hmmmm... There are some flaws I can see:
database.php
$host = "us-cdbrbababababableardb.net";
$user = "b9bababababefc";
$pass = "9c4ababab";
$dbname = "heroku_aabababab49";
$DBH = null;
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
file that must insert data
<?php
include 'database.php';
$_POST['name'] = 'test';
$_POST['message'] = 'test';
$_POST['date'] = 'test';
var_dump($_POST);
if(isset($_POST['name']) && isset($_POST['message'])){
$data = array(
'name' => $_POST['name'],
'shout' => $_POST['message'],
'date' => $_POST['date']
);
try {
// NOTICE: prepare() used and VALUES instead of VALUE
$STH = $DBH->prepare("INSERT INTO shouts (name, message, date) values (:name, :message, :date)");
$STH->bindParam(':name', $_POST['name']);
$STH->bindParam(':message', $_POST['message']);
$STH->bindParam(':date', $_POST['date']);
// NOTICE: $data has allready been supplied by bindParam()
$STH->execute();
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
These are just the first few things I could find wrong with the code... Try reading up on the PDO tutorials and functions for better info on what they would need as input.

Data not entered into database from PHP

I am trying to enter data into a database with PHP.
Here is my code:
<?php
$username = 'username'; //username for database
$password = 'password'; //password for database
$hostname = 'localhost'; //host
$db_name = 'db_testdrubin'; //name of database
$db_selected = mysqli_connect($hostname, $username, $password, $db_name)//specify database
or die ("unable to connect");
if(isset ($_POST['submit'])){
$ID = ($_POST['ID']);
$fname = ($_POST['fname']);
$lname = ($_POST['lname']);
$address = ($_POST['address']);
$city = ($_POST['city']);
$state = ($_POST['state']);
$zip = ($_POST['zip']);
$phone = ($_POST['phone']);
$email = ($_POST['email']);
$books = ($_POST['books[]']);
$comments = ($_POST['comments']);
}
else{
echo'<p>not submitted</p>';
}
//up until this point the code works fine
$query = 'INSERT INTO Student VALUES ($ID, $fname, $lname, $address, $city, $state, $zip, $phone, $email, $books, $comments)';
$success = $db_selected->query($query);
if($success){
$count = $db_selected->affectd_rows;
echo '<p>$count were added</p>';
}
else{
echo '<p>error</p>';
}
?>
I know that the information is being read from the html form correctly because I have checked by printing the individual variables. I am not getting any error messages when I submit the form, just the "error" echo statement from the if/else statement, and no data is entered into the database.
I have also tried this:
if (!mysql_query($db_selected, $query)){
echo '<p>error</p>';
}
with the same results.
Change this
$query = 'INSERT INTO Student VALUES ($ID, $fname, $lname, $address, $city, $state, $zip, $phone, $email, $books, $comments)';
to
$query = "INSERT INTO Student VALUES ($ID, '$fname', '$lname', '$address', '$city', '$state', $zip, $phone, '$email', '$books', '$comments')";
I mean to say if its string then do like '$string' and also use
$db_selected->real_escape_string($stringval);
and use
echo $db_selected->error;
to check the error you got.
$ins="insert into Student (`id`,`fname`,`lname`,`address`,`city`,`state`,`zip`,`phone`,`email`,`books`,`comments`)values
('".$ID."','".$fname."','".$lname."','".$address."','".$city."','".$state."','".$zip."','".$phone."','".$email."','".$books."','".$comments."')";
mysql_query($ins);

PDO Insert not working (PHP/MySQL)

After days of trial and error, I finally replaced my standard mysql code with PDO. Everything seems to be working just fine except for the last part where the app needs to INSERT user (name, email and time of signup) into database. After clicking submit, page just turns blank.
I don't see what is wrong with the code, so I would appreciate if you could help me out.
<?php
////Database connection values
$dsn = 'mysql:host=host; dbname=name; charset=utf8';
$db_user = 'username';
$db_pass = 'password';
//Database connection
$db = new PDO($dsn, $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Enable Exception error mode
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // Use PDO safely = Turn off prepare emulation
// Databse connection check
if($db){
print "connected to the db " . "<br />";
}
//Declare values
$name = "";
$email = "";
$userMsg = "";
if ($_POST['name'] != "") {
$name = $_POST['name'];
$email = $_POST['email'];
//MySQL SELECT Query
$stmt = $db -> prepare ("SELECT * FROM newsletter WHERE email=?");
$stmt-> bindValue(1, $email);
$stmt -> execute ();
//Error - No email
if (!$email) {
$userMsg = '<br /><br /><h4><font color="FF0000">Please type an email address ' . $name . '.</font></h4>';
} // End email-input check
//Error - Email already in the system
else if ($stmt -> rowCount() > 0) {
$userMsg = '<br /><br /><h4><font color="FF0000">' . $email . ' is already in the system.</font></h4>';
} // End Row check
//OK - insert user into database
else {
$insert = $db -> prepare ("INSERT INTO newsletter (name, email, dateTime) VALUES(:name, :email, ,NOW())");
$insert -> execute(array(':name' => $name, ':email' => $email));
//Success! - Notify user
$userMsg = '<br /><br /><h4><font color="0066FF">Thanks ' . $name . ', you have been added successfully.</font></h4>';
$name = "";
$email = "";
} // End INSERT
}
?>
VALUES(:name, :email, ,NOW())"
should be
VALUES(:name, :email, NOW())"

Categories