PHP application not saving data to MySQL database - php

I am creating my first Wordpress plugin and have been stumped for a couple of days. So far I am trying to just get my plugin to save data to the MySQL database on my localhost. When I enter info into the form it creates a new row, which auto increments, but does not pass any of the info that I have entered into the database.
I understand that I have to clean up a lot of this code before I use it but I am just starting and stumped on this particular issue.
Here is the relevant code;
dvi_customer_info.php file
<?php
require('database.php');
require('customer_info_functions.php');
if ($action == 'add_customer') {
$rep = $_POST['rep'];
$business = $_POST['business'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$name = $_POST['name'];
$email = $_POST['email'];
}
add_customer($rep, $business, $address, $phone, $name, $email);
include('dvi_customer_info_sheet.php');
customer_info_functions.php file
<?php
function add_customer($rep, $business, $address, $phone, $name, $email) {
global $db;
$query = "INSERT INTO customers
(repName, customerBusiness, customerAddress, customerPhone, customerName, customerEmail)
VALUES
('$rep', '$business', '$address', '$phone', '$name', '$email')";
$db->exec($query);
}
?>
dvi_customer_info_sheet.php file
<body>
<h1>Customer Info Sheet</h1>
<form action="dvi_customer_info.php" method="post" id="customer_info_sheet_form">
<input type="hidden" name="action" value="add_customer" />
<label>Name of Rep:</label>
<input type="input" name="rep" />
<br />
<label>Name of Business:</label>
<input type="input" name="business" />
<br />
<label>Address:</label>
<input type="input" name="address" />
<br />
<label>Phone #:</label>
<input type="input" name="phone" />
<br />
<label>Name of Decision Maker:</label>
<input type="input" name="name" />
<br />
<label>Email:</label>
<input type="input" name="email" />
<br />
<label> </label>
<input type="submit" value="Add Customer" />
<br /> <br />
</form>
</body>

"INSERT INTO customers
(repName, customerBusiness, customerAddress, customerPhone, customerName, customerEmail)
VALUES
(\"$rep\", $business,...)
(Use double quotes "$rep" or don't use any quotes $business ( use this option) as anything within single quotes is taken as it is i.e a string constant and hence the variable inside that didn't get substituted by it's value

Try This
$query = "INSERT INTO customers
(repName, customerBusiness, customerAddress, customerPhone, customerName, customerEmail)
VALUES
('".$rep."', '".$business."', '".$address."', '".$phone."', '".$name."', '".$email."')";
And Also
I am not clear About your if condition if($action =='add_customer' ) instead of that try
if(isset($_POST['add_customer']))
What is $action?

you can use wordpress default action to insert record in to database like this below code it's sure to insert your record in mysql database.
You have no need to use function to just insert record in database just put this code in dvi_customer_info.php file
<?php
require('database.php');
require('customer_info_functions.php');
global $wpdb;
if ($action == 'add_customer') {
$rep = $_POST['rep'];
$business = $_POST['business'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$name = $_POST['name'];
$email = $_POST['email'];
$your_table_name_here = $wpdb->prefix . 'yourdatanase_table';
$data = array(
'repName' => $rep,
'customerBusiness' => $business,
'customerAddress' => $address,
'customerPhone' => $phone,
'customerName' => $name,
'customerEmail' => $email
);
$idsa = $wpdb->insert($your_table_name_here, $data);
if ($idsa) {
echo '<p class="alert-box success tfamsg">Franchise Setting Inserted.</p>';
}
}
include('dvi_customer_info_sheet.php');
?>
Now it will insert record in database you had also change your database table $your_table_name_here.
Thanks

Related

Attempting to Submit HTML Form to Database Has Blank Output

I am new to PHP and web development, and trying to create an HTML form that will submit data into MYSQL.
Upon checking phpmyadmin after submission of the form, it shows that there has been a row submitted,
however the row is completely blank. I had a problem before this one, that instead of a blank row, it would be "1" submitting instead of the data inserted into the HTML form. Now, no data submits into the database.
Here is the PHP:
<?php
Include("connection.php");
// HTML Identification
$lname = isset($_POST['lastname']);
$fname = isset($_POST['firstname']);
$email = isset($_POST['email']);
$phone = isset($_POST['phonenum']);
$addr = isset($_POST['address']);
$city = isset($_POST['city']);
$state = isset($_POST['state']);
$zip = isset($_POST['zipcode']);
//Database Insertion
$sql= "INSERT INTO CustomerInfo (LastName, FirstName, Email, PhoneNum, Address, City, State, ZipCode)
VALUES ('$lname', '$fname', '$email', '$phone', '$addr', '$city', '$state', '$zip')";
// Insertion
$ds= mysqli_query($conn, $sql);
// - Insertion Confirmation
if($ds)
{
print 'Row Inserted!';
print ' Response Recorded!';
}
?>
The HTML Form:
!DOCTYPE html>
<html>
<head>
<title> GS Entry Form </title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css#2/out/water.css" </link>
<style>
h1 {text-align: center;}
h2 {text-align: center;}
</style>
</head>
<body>
<h1>Customer Entry Form</h1>
<h2>Please Input Contact Information</h2>
<form action="database.php" method="POST">
First Name:<br />
<input type="text" name="firstname" />
<br /><br />
Last Name:<br />
<input type="text" name="lastname" />
<br /><br />
Email:<br />
<input type="text" name="email" />
<br /><br />
Phone Number:<br />
<input type="text" name="phonenum"/>
<br /><br />
Address:<br />
<input type="text" name="address"/>
<br /><br />
City:<br />
<input type="text" name="city"/>
<br /><br />
State:<br />
<input type="text" name="state"/>
<br /><br />
Zip Code:<br />
<input type="text" name="zipcode"/>
<br /><br />
<button type="button" name= "submit" value= "submit" />
</form>
</body>
</html>
Here, also, is the connection.php referenced:
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create Connection
$conn= mysqli_connect("$servername:3306","$username","$password","$dbname");
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " .$conn->connect_error);
}
else echo "Connection successful! "
?>
I don't think it has anything to do with the connection, but I figured I would post it to cover all the bases. The attached imgur picture is what my database has been looking like after submissions have been made.
I truly am not sure what to do now, any help would be greatly appreciated.
Thank you! -G
EDIT:
This is what my PHP code looks like after the changes suggested from #EinLinuus:
<?php
Include("connection.php");
// HTML Identification POST
if(isset($_POST['firstname'])) {
$fname = $_POST['firstname'];
}else{
die("Firstname is missing");
}
if(isset($_POST['lastname'])) {
$lname = $_POST['lastname'];
}else{
die("Lastname is missing");
}
if(isset($_POST['email'])) {
$email = $_POST['email'];
}else{
die("Email is missing");
}
if(isset($_POST['phone'])) {
$phone = $_POST['phone'];
}else{
die("Phone Number is missing");
}
if(isset($_POST['addr'])) {
$addr = $_POST['addr'];
}else{
die("Address is missing");
}
if(isset($_POST['city'])) {
$city = $_POST['city'];
}else{
die("City is missing");
}
if(isset($_POST['state'])) {
$state = $_POST['state'];
}else{
die("State is missing");
}
if(isset($_POST['zip'])) {
$zip = $_POST['zip'];
}else{
die("Zip Code is missing");
}
//Database Insertion
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt= $conn->prepare("INSERT INTO CustomerInfo(FirstName, LastName, Email, PhoneNum, Address, City, State, ZipCode) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssssss', $fname, $lname, $email, $phone, $addr, $city, $state, $zip);
$stmt->execute();
// Insertion
$sql= mysqli_query($conn, $stmt);
// - Insertion Confirmation
if($ds)
{
print 'Row Inserted!';
print ' Response Recorded!';
}
$stmt->close();
$conn->close();
?>
My HTML remains the same, besides adding ID attributes to each variable to no effect. I appreciate the help!
The isset function returns if the variable is declared or not -> the return type is a boolean.
$test = [
"hello" => "world"
];
var_dump(isset($test["hello"])); // bool(true)
var_dump(isset($test["something"])); // bool(false)
You can use isset to check if the field exists in the $_POST variable, but don't save the result of the isset function to the database. If you do so, the boolean will be converted to a number (true => 1, false => 0) and this number gets stored in the database.
Example:
if(isset($_POST['lastname'])) {
die("lastnameis missing");
}
$lname = $_POST['lastname'];
Security
This code is vulnerable to SQL Injections. You should never trust user input. I'd recommend to use prepared statements here:
$stmt = $mysqli->prepare("INSERT INTO CustomerInfo (LastName, FirstName, ...) VALUES (?, ?, ...)");
$stmt->execute([$lname, $fname]);
In the SQL statement, replace the actual values with ?. Now you can execute the statement and pass the values to the execute function. In the example above, $lname will replace the first ?, $fname the second, ...

How to use a UPDATE clause and a INSERT clause in the same file?

Here is my form in my html page.. the hidden inputs are for the notification INSERT.. and the "text" input & the "range" input are for the UPDATE order progress ALSO the UPDATE statement is working just not the INSERT..
<form method="POST" action="../PHP/ordprogress.php">
<input type="hidden" value="<?php echo $fetch['username']?>" name="username">
<input type="hidden" value="Admin" name="name">
<input type="hidden" value="Update!" name="notif">
<input type="hidden" value="Your progress has been updated!" name="details">
<input type="hidden" value="<?php echo date('Y/m/d H:i:s'); ?>" name="date">
<input type="hidden" value="unread" name="status">
<input type="text" name="uid" value="" placeholder="Order Number..">
<input type="range" step="25" min="0" max="100" value="50" name="ordprogress" class="sliderper" id="myRange">
<button type="submit" value="Update" name="Update">Update</button>
</form>
And here is my ordprogress.php script, it should just insert a row (notification) after the order progress has been updated..I had it working twice and then I tried to fix something then it stopped working and when I reverted the code it still didn't work lol
<?php
session_start();
require("/var/www/vhosts/mysite.co.uk/httpdocs/PHP/connect.php");
if (isset($_POST['Update'])) {
$ordprogress = $_POST['ordprogress'];
$uid = $_POST['uid'];
$stmt = "UPDATE device_repairs SET ordprogress = :ordprogress WHERE uid = :uid";
$stmt = $dbh->prepare($stmt);
$stmt->bindParam(':ordprogress', $_POST['ordprogress'], PDO::PARAM_STR);
$stmt->bindParam(':uid', $_POST['uid'], PDO::PARAM_STR);
$stmt->execute();
$uid = $_POST['uid'];
$username = $_POST['username'];
$name = $_POST['name'];
$notif = $_POST['notif'];
$details = $_POST['details'];
$date = $_POST['date'];
$status = $_POST['status'];
$sql = 'INSERT INTO `notifications` (uid, username, name, notif, details, date, status) VALUES (:uid, :username, :name, :notif, :details, :date, :status)';
$inst = $dbh->prepare($sql);
$inst->execute(['uid' => $uid, 'username' => $username, 'name' => $name, 'notif' => $notif, 'details' => $details, 'date' => $date, 'status' => $status]);
?>
<meta http-equiv="refresh" content="0; URL=https://www.mysite.co.uk/Profile/admin.php" />
<?php
}
?>

How to Store a sessions first name in a mysql database when a form is submitted?

How can I pass the Session into the database when the form is submitted. I try to make this simple for everyone to understand. Thanks for helping me out. I don't quite understand.
PHP- I do have session start as well.
<?php
require('Conn.php');
$statement = $link->prepare("INSERT INTO Database(Client_FN, email) VALUES( :CFN, :Email)");
$ClientFN = $_POST['Client_FN']; <-- I want to insert $_SESSION['first_name'] into the database. - Not sure how to do this?
$ClientEmail = $_POST['email'];
$statement->execute(array(
":CFN" => "$ClientFN");
":Email" => "$ClientEmail");
// Echo Successful attempt
echo "<p Data added to database.</p></br></br>";
$statement = null;
$link = null;
?>
HTML
<label> Name: <input name="Client_FN" type="text"
class="form-control" id="" value="<?php echo $_SESSION['first_name']; ?>"> </label> </div>
<label> Name: <input name="email" type="text"
class="form-control" id="" value=""> </label> </div>

I am having trouble saving my PHP data to MySQL database

My .php page is connected to mySql database successfully. It can see the table and pull from the tables but won't save data from the text-box in my php form to the database.
config.php
<?php
try{
$db = new PDO("mysql:host=localhost;dbname=nolarec;port=3307","root","");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch(Exception $e) {
echo $e->getMessage();
exit;
}
?>
fball_event.php
<form method="post" action="fball_create.php">
<input type="hidden" name="submit" value="true">
<fieldset>
<legend>New Event</legend>
Id: <input type="text" name="id"/> <br/>
Name: <input type="text" name="name"/> <br/>
Time: <input type="text" name="time"/> <br/>
Type: <input type="text" name="type"/> <br/>
</fieldset>
<br />
<input type="submit" value="Create New Event" />
</form>
<?php
require_once('config.php');
if (isset($_POST['submit'])){
include ('config.php');
$id = $_POST['id'];
$name = $_POST['name'];
$time = $_POST['time'];
$type = $_POST['type'];
$results = $db->prepare ("INSERT INTO nolarec.fball_event (id, name, time, type) VALUES ('$id','$name','$time','$type')");
}
?>
First of all you should be using placeholders for your data inputs in the query, second of all you need to actually execute it, you've just prepared it. Try:
$id = $_POST['id'];
$name = $_POST['name'];
$time = $_POST['time'];
$type = $_POST['type'];
$results = $db->prepare ("INSERT INTO nolarec.fball_event (id, name, time, type) VALUES (:id,:name,:time,:type)");
$results->bindValue(":id", $id);
$results->bindValue(":name", $name);
$results->bindValue(":time", $time);
$results->bindValue(":type", $type);
$results->execute();

Inserting data into mysql using php

Ive been having difficulties trying to load form data into my database.
Im trying to input theatre info using the following php script.
<?php
require('connect.php');
if (isset($_POST['theatre_name']) && isset($_POST['website'])){
$theatre_name = $_POST['theatre_name'];
$phone_number = $_POST['phone_number'];
$website = $_POST['website'];
$num_screens = $_POST['num_screens'];
$address = $_POST['address'];
$city = $_POST['city'];
$queryd = "INSERT INTO `Theatres` (theatre_name, phone_number, website,
num_screens, address, city)
VALUES ('$theatre_name', '$phone_number', '$website', '$num_screens',
'$address', '$city')";
$result = mysql_query($queryd);
if($result){
$msg = "Theatre created.";
}
}
?>
The following is my html code:
<!DOCTYPE html>
<html>
<body>
<!-- Form for creating theaters -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<form action="theatredb.php" method="POST">
<p><label>Theater Name : </label>
<input type = "text" name= "theatre_name" placeholder= "Theater Name" /></p>
<p><label>Phone Number : </label>
<input type = "text" name= "phone_number" placeholder="Phone Number" /></p>
<p><label>Website : </label>
<input type="text" name= "website" placeholder ="Website" /></p>
<p><label> Number of Screens : </label>
<input type= "text" name="num_screens" placeholder ="Number of screens" /></p>
<p><label>Address : </label>
<input type="text" name="address" placeholder="Address" /></p>
<p><label>City : </label>
<input type="text" name="city" required placeholder="City Name" /></p>
<input class="btn register" type="submit" name="submit" value="done" />
</form>
</div>
</body>
</html>
I was wondering if anyone could give me some guidance with regards to what I'm doing wrong. Ive been stuck with this problem for hours and don't know what I'm doing wrong.
EDIT: I dont get an error per say, but the data does not get uploaded into the database. For some reason my query isnt working.
try this
<?php
require('connect.php');
if (isset($_POST['theatre_name']) && isset($_POST['website'])){
$theatre_name = $_POST['theatre_name'];
$phone_number = $_POST['phone_number'];
$website = $_POST['website'];
$num_screens = $_POST['num_screens'];
$address = $_POST['address'];
$city = $_POST['city'];
//**change code to below**
$queryd = "INSERT INTO `Theatres` (theatre_name, phone_number, website, num_screens, address, city) VALUES ('{$theatre_name}', '{$phone_number}', '{$website}', '{$num_screens}', '{$address}', '{$city}')";
$result = mysql_query($queryd);
if($result){
$msg = "Theatre created.";
}
}
?>
link single quoted
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
I once had the same issue. Your query variable should look like this:
$queryd = "INSERT INTO `Theatres` (theatre_name, phone_number, website,
num_screens, address, city)
VALUES ('".$theatre_name."', '".$phone_number."', '".$website."',
'".$num_screens."', '".$address."', '".$city."')";
Explanation: In your original query, you would have just inserted literally $theatre_name, not the variables value. In order to get around this, you have to close the string, with ", concatenate the variable to the preceding string, with . , and then re open the string.
Also, I don't know what version of PHP you are using, but you should be using mysqli_query(). mysql_query() is depreciated as of PHP v5.5. PHP manual entry.

Categories