MySQL query not inserting row - php

I have a form in my handler:
<form action="../submitcomment.php" method="post">
<input maxlength=100 size=60 type="text" name="IP" value="' . $ip . '" readonly="readonly" hidden="hidden">
<input maxlength=100 size=60 type="text" name="BlogId" value="' . $blogId . '" readonly="readonly" hidden="hidden">
<input maxlength=100 size=60 type="text" name="Date" value="' . $date . '" readonly="readonly" hidden="hidden">
<input maxlength=100 size=60 type="text" name="Name" placeholder="Enter Your Name">
<input maxlength=100 size=60 type="text" name="Email" placeholder="Enter Your Email">
<input maxlength=100 size=60 type="text" name="Comment" placeholder="Enter Your Comment">
<br>
<input type="submit" name="Submit" value="Submit Your Comment">
</form>
The action is submitcomment.php:
$ip = $_POST['IP'];
$BlogId = $_POST['BlogId'];
$Date = $_POST['Date'];
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Comment = $_POST['Comment'];
$blog = new Blogs();
if (isset($_POST['Submit']))
{
$addComment = $blog->insertComment($ip, $BlogId, $Date, $Name, $Email, $Comment);
header('Location: http://www.ryan.archi.dev.netsite.co.uk/Blog?success=1');
}else{
header('Location: http://www.ryan.archi.dev.netsite.co.uk/Blog?fail=1');
}
which reference a function in my class:
function insertComment($ip, $BlogId, $Date, $Name, $Email, $Comment)
{
$query = "INSERT INTO BlogComments (Name, Comment, IPAddress, Email, BlogId, Date) VALUES ('$Name', '$Comment', '$ip', '$Email', '$BlogId', '$Date')";
$oDatabase = new database;
$connection = $oDatabase->Connect();
$result = mysql_query ($query, $connection);
return $result;
}
The attempt to insert does not return or raise any errors.
As far as I'm aware this should be working, Can you spot what I am doing wrong?

Problem is with the column named Date - date is a reserved word (I guess of all known RDBMS).
You have to escape this word in Your query:
INSERT INTO BlogComments (Name, Comment, IPAddress, Email, BlogId, `Date`) VALUES ('$Name', '$Comment', '$ip', '$Email', '$BlogId', '$Date')
Also Your code gives anybody a chance to do a SQL injection attack therefore You should at least escape any user input or better use MySQLi or PDO.
You can do the escaping by php function http://php.net/mysql_real_escape_string :
$ip = mysql_real_escape_string($_POST['IP']);
$BlogId = mysql_real_escape_string($_POST['BlogId']);
$Date = mysql_real_escape_string($_POST['Date']);
$Name = mysql_real_escape_string($_POST['Name']);
$Email = mysql_real_escape_string($_POST['Email']);
$Comment = mysql_real_escape_string($_POST['Comment']);

Did you debug it? Is the connection to the database established successfully? You did no mysql escaping maybe the insert query fails.

Related

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

PHP TO MySQL secured with MySQLi and hyperlink redirect not working once submitted

I had a Freelancer work on a site for me and could not finish my project which should of been of ease to him and I need to get this fully running to be ready by morning.
This is my PHP code which I had to create in a hurry
<?php
$con = mysqli_connect('localhost','dbuser','password'
if(!$con)
{
echo 'Not Connected To Server';
}
if(!mysqli_select_db($con,'DBName'))
{
echo 'Database Not Selected';
}
$UserN = $_POST['UserN'];
$FullN = $_POST['FullN'];
$Adrs = $_POST['Adrs'];
$Email = $_POST['Email'];
$PhoneN = $_POST['PhoneN'];
$sql = "INSERT INTO UserIn (UserN, FullN, Adrs, Email, PhoneN) VALUES ('$UserN', '$FullN', '$Adrs', '$Email', '$PhoneN')";
if(!mysqli_query($con,$sql))
{
echo 'Not Inserted';
}
else
{
echo 'Inserted';
}
header("refresh:2; url=survey.html
?>
this is PHP
this is my Form
<div class="form-con">
<form actoin="insert.php" method="post">
<label>Username</label><br>
<input type="text" name="UserN" placeholder="Your Username" ><br>
<label>Full Name</label><br>
<input type="text" name="FullN" placeholder="Full Name"><br>
<label>Full Address</label><br>
<textarea type="text" rows="4" cols="50" name="Adrs" placeholder="Address"></textarea><br>
<label>Email Address</label><br>
<input type="email" name="Email" placeholder="Email Address"><br>
<label>Phone Number</label><br>
<input type="text" name="PhoneN" placeholder="Phone Number"><br>
<div class="btn">
<button type="submit">Submit</button>
</div>
</form>
</div>
Please help me I want to also secure the form with
Using MySQLi (for MySQL):
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
From here
https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1
please help.
New PHP
<?php
$dbh = new PDO("mysql:host=$host;dbame=$dbname",$user,$pass);
$UserN = mysqli_real_escape_string($con, $_POST['UserN']);
$FullN = mysqli_real_escape_string($con, $_POST['FullN']);
$Adrs = mysqli_real_escape_string($con, $_POST['Adrs']);
$Email = mysqli_real_escape_string($con, $_POST['Email']);
$PhoneN = mysqli_real_escape_string($con, $_POST['PhoneN']);
$stmt = $dbh->prepare("INSERT INTO UserIn (UserN, FullN, Adrs, Email, PhoneN) VALUES ('$UserN','$FullN','$Adrs','$Email','$PhoneN')"); //Insert query
$stmt->execute($UserN, $FullN, $Adrs, $Email, $PhoneN);
header("refresh:1; url=survey.html");
?>
You can do 2 things to secure from SQL-injection-
1) use $UserN = mysqli_real_escape_string($con, $_POST['UserN']); instead of
$UserN = $_POST['UserN'];
2) for connecting to MySql, use PDO like so-
$dbh = new PDO("mysql:host=$host;dbame=$dbname",$user,$pass);
Then the Insert query $sql = "INSERT INTO UserIn (UserN, FullN, Adrs, Email, PhoneN) VALUES ('$UserN', '$FullN', '$Adrs', '$Email', '$PhoneN')";
becomes-
$stmt = $dbh->prepare("INSERT INTO UserIn (UserN, FullN, Adrs, Email, PhoneN) VALUES (?,?,?,?,?)"); //Insert query
$stmt->execute($UserN, $FullN, $Adrs, $Email, $PhoneN);

PHP application not saving data to MySQL database

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

Row being added to MySQL database but no other data from the html form using PHP

The data from the form is not getting saved into the database but a row is being added, I am hosting with Go Daddy. It worked perfectly on my local but now live seems to be not working. Please find below the code I am using:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$fName = mysql_real_escape_string($_POST['fName']);
$surname = mysql_real_escape_string($_POST['surname']);
$postcode = mysql_real_escape_string($_POST['postcode']);
$tel = mysql_real_escape_string($_POST['tel']);
$mobile = mysql_real_escape_string($_POST['mobile']);
$email = mysql_real_escape_string($_POST['email']);
$bool = true;
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db name", $con);
$sql="INSERT INTO customer (custNo, fName, surname, postcode, tel, mobile, email, timestamp)
VALUES (NULL, '$fName','$surname','$postcode', '$tel', '$mobile', '$email', 'CURRENT_TIMESTAMP')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
} else{
echo "Successfully Registered ";
}
}
mysql_close($con)
?>
and here is the html form
<form action="insert.php" method = "post">
<fieldset>
<legend>Register</legend>
<div class="col-md-4">
<label for='fName'>Enter name:</label>
<input type= "text" name = "fName" required="required" maxlength="50"/> <br/>
</div>
<div class="col-md-4">
<label for='surname'>Enter surname:</label>
<input type= "text" name="surname" maxlength="50" required="required"/> <br/>
</div>
<div class="col-md-4">
<label for='postcode'>Enter postcode:</label>
<input type= "text" name="postcode" maxlength="7"/> <br/>
</div>
<div class="col-md-4">
<label for='tel'>Enter home no:</label>
<input type= "text" name="tel" maxlength="50" /> <br/>
</div>
<div class="col-md-4">
<label for='mobile'>Enter mobile no:</label>
<input type= "text" name="mobile" maxlength="50"/> <br/>
</div>
<div class="col-md-4">
<label for='email'>Enter email * </label>
<input type= "text" name="email" required="required"/> <br/></br>
</div>
<input type="submit" value="Register"/>
</fieldset>
</form>
First :
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
If you didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);
This means the query sent to MySQL would be:
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''
This would allow anyone to log in without a valid password.
To your problem !
All your variables are empty due to this fact ...
A MySQL connection is required before using mysql_real_escape_string()
otherwise an error of level E_WARNING is generated, and FALSE is
returned.
put your mysql_real_escape_string() after connect.
$con = mysql_connect("localhost","username","password");
if (!$con) { ...}
mysql_select_db("db name", $con);
//-------------- next after connect not before !!! --------
$fName = mysql_real_escape_string($_POST['fName']);
[...]
$email = mysql_real_escape_string($_POST['email']);
$bool = true;
$sql="INSERT INTO customer (...) VALUES (...)";
It may be due to the varibales.
try changing the $sql line to this
$sql = "INSERT INTO customer (custNo, fName, surname, postcode, tel, mobile, email, timestamp) VALUES (NULL, '" . $fName . "', '" . $surname . "', '" . $postcode . "', '" . $tel . "', '". $mobile . "', '" . $email . "', 'CURRENT_TIMESTAMP')";

Code only sends name to DB and sends phone number to email field

I updated code per suggestions but now it only sends name to DB and sends phone number to email field. I have copied new code below.
Form:
<form action="processor.php" method="post">
<div class="field-box">
<label>Name:</label>
<input type="text" name="name" />
</div>
<div class="field-box">
<label>Age:</label>
<input type="text" name="age" />
</div>
<div class="field-box">
<label>Phone Number:</label>
<input type="text" name="phone" />
</div>
<div class="field-box">
<label>Email:</label>
<input type="text" name="email"/>
<input type="submit">
</form>
And the SQL to send the data on processor.php:
function sendData() {
//Connecting to sql db.
$connect = mysqli_connect("XXXXXX","XXXXXXXX","XXXXXXX","XXXXXXX");
//setting values from HTML form
$name = mysqli_real_escape_string($connect, $_POST['name']);
$age = mysqli_real_escape_string($connect, $_POST['age']);
$phone = mysqli_real_escape_string($connect, $_POST['phone']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
//Sending form data to sql db
mysqli_query($connect,"INSERT INTO users (name, age, phone, email) VALUES ('$name', '$age', '$phone', '$email')");
}
sendData();
Just switch out the existing query with this one and it'll work. Cheers.
mysqli_query($connect,"INSERT INTO users (name, age, phone, email) VALUES ('" . $name . "', '" . $age . "', '" . $phone . "', '" . $email . "')");
Try another insert type
mysqli_query($connect,"INSERT INTO users SET name='$name', age='$age',phone='$phone', email='$email')");
First of all try to insert into the db with static parameters. I mean something like this
mysqli_query($connect,"INSERT INTO users (name, age, phone, email) VALUES ('name', 'age', 'phone', 'email')");
And check if your query works ! But you can otherwise try this one
mysqli_query($connect,"INSERT INTO users (name, age, phone, email) VALUES ('" . $name . "', '" . $age . "', '" . $phone . "', '" . $email . "')");
I suggest you use Prepared Statements and if possible PDO
Good Luck

Categories