PHP Mysql submit form - php

i am trying to submit data from a html form using php to a sql database.
It completed up to part 5 but doesn't appear to be any actual data in any of the table rows apart from the auto increment userID. Also is this code protected from SQL Injection?
Also what is the best way to input a datestamp into the SQL database? for example a ClientSince field.
Here is my clientsubmit.php
<?php
// Create connection
echo "Made it! Part 1";
$con=mysqli_connect("xxx","xxx","xxx","xxx");
echo "Made it! Part 2";
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$txtNam = mysql_real_escape_string($_POST["name"]);
$txtEmail = mysql_real_escape_string($_POST["email"]);
$txtSlots = mysql_real_escape_string($_POST["slotcount"]);
$txtSecurity = mysql_real_escape_string($_POST["passcode"]);
echo "Made it! Part 3";
$sql = "INSERT INTO accounts (name, email, slotCount, securityCode) Values('$txtNam','$txtEmail','$txtSlots','$txtSecurity')";
echo "Made it! Part 4";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Made it! Part 5";
mysqli_close($con);
?>
And here is my form:
<form name="form" class="form" action="clientsubmit.php" method="post">
<input type="text" name="sum2" readonly hidden="true" onChange="updatesum()" value="1.5"/><br>
Ingame Name: <input type="text" name="name" class="txtbox" /><br><br>
Email Address: <input type="text" name="email" class="txtbox" /><br><br>
Passcode: <input type="text" name="passcode" class="txtbox2" /><br><br>
Slot Count: <input type="text" name="slotcount" onChange="updatesum()" class="txtbox2" value="10"/><br><br>
Per Month: <input name="sum" readonly class="txtboxtotal" style="border: 0px;" value="15"> Million<br><br>
<input type="submit">
</form>
Added these:
echo "Made it here! 3 ";
echo " ";
echo $txtNam;
echo " ";
echo $txtEmail;
echo " ";
echo $txtSlots;
echo " ";
echo $txtSecurity;
echo " ";
and it appears that the variables are not holding any data before submitted to the database.
Got it working with the help of you guys, here is the finished code:
<?php
// Create connection
$con=mysqli_connect("xxxx","xxxx","xxxx","xxxx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$txtNam = mysqli_real_escape_string($con, $_POST["name"]);
$txtEmail = mysqli_real_escape_string($con, $_POST["email"]);
$txtSlots = mysqli_real_escape_string($con, $_POST["slotcount"]);
$txtSecurity = mysqli_real_escape_string($con, $_POST["passcode"]);
$sql = "INSERT INTO accounts (name, email, slotCount, securityCode) Values('$txtNam','$txtEmail','$txtSlots','$txtSecurity')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>

The issue is you are using mysql_real_escape_string() and using mysqli_*()
change mysql_real_escape_string() to mysqli_real_escape_string()
$txtNam = mysqli_real_escape_string($con, $_POST["name"]);
$txtEmail = mysqli_real_escape_string($con,$_POST["email"]);
$txtSlots = mysqli_real_escape_string($con,$_POST["slotcount"]);
$txtSecurity = mysqli_real_escape_string($con,$_POST["passcode"]);

You mentioned above submit.php and you post form at clientsubmit.php.

Related

Database not updating correctly in PHP / MySQL [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I've got a database with a Users table which I'm trying to update.
Currently I have customers.php, which displays form fields with the user information so it can be updated.
This form points to edit_customer_processor.php , which takes the new values, puts them into a MYSQL query... and then despite the query working correctly when I query the DB via the PHPMyAdmin command line, the record doesn't update.
customers.php
<?php
session_start();
if(!$_SESSION["logged_in"]){
header("location:home.php");
die;
}
?>
<?php include 'header.html'; ?>
<div id='maincontent'>
<?php
if (isset($_GET["id"])){
$customer_id = $_GET["id"];
require_once('config.php');
$customer_query = "SELECT * FROM customer WHERE customer_id = $customer_id";
$customer_results = mysql_query($customer_query, $conn);
if (!$customer_results) {
die ("Error selecting car data: " .mysql_error());
}
else {
while ($row = mysql_fetch_array($customer_results)) {
echo "<h3>Edit Customer</h3>";
echo "<FORM method='post' action='edit_customer_processor.php'>";
echo '<p> Name: <input type="text" name="name" size = "40" value=' . $row[name] . '></p>';
echo '<p> Address: <input type="text" name ="address" size="40" value=' . $row[address] . '></p>';
echo '<p> Email: <input type="text" name="email" value=' . $row[email] . '></p>';
echo '<p> Phone: <input type ="text" name="phone" size="20" value=' . $row[phone] . '></p>';
echo '<input type ="hidden" name="customer_id" value="' . $row[customer_id] . '">';
echo '<input type ="hidden" name="formtype" value="edit_customer">';
echo '<input type="submit" name="submit" value= "Update">';
echo '</form>';
}
}
} else {
// If there isn't an ID, display the New Customer form and all customers below, with links
// to their edit pages.
echo "<h3>Enter new customer information and submit.</h3>";
echo "<FORM method='post' action='new_customer_processor.php'>";
echo '<p> Name: <input type="text" name="name" size = "40"></p>';
echo '<p> Address: <input type="text" name ="address" size="40"></p>';
echo '<p> Email: <input type="text" name="email"></p>';
echo '<p> Phone: <input type ="text" name="phone" size="20"></p>';
echo '<input type ="hidden" name="formtype" value="new_customer">';
echo '<input type="submit" name="submit" value= "Submit">';
echo '<input type ="reset" name="reset" value ="Reset">';
echo '</form>';
require_once('config.php');
echo "<h3>Current Customers</h3>";
$query = "SELECT * FROM customer";
$results = mysql_query($query, $conn);
if (!$results) {
die ("Error selecting customer data: " .mysql_error());
}
else {
// In the absence of an ID, all customers will be displayed down
// the bottom of the page
while ($row = mysql_fetch_array($results)) {
echo "<a href=customers.php?id=";
echo $row[customer_id];
echo "><p> $row[name] </p></a>";
echo "<p> $row[address] </p>";
echo "<p> $row[phone] </p>";
echo "<p> $row[email] </p>";
}
}
}
?>
Back to Customers Page
</div>
<?php include 'footer.html' ?>
edit_customer_processor.php
<?php include 'header.html' ?>
<div id="maincontent">
<?php
// Pulling in hidden customer ID from post value
$mysqli = new mysqli( 'localhost', 'root', 'root', 'w_c_a' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// Insert our data
$sql = mysql_query("UPDATE customer
SET name = '".mysql_real_escape_string($_POST['name'])."',
address = '".mysql_real_escape_string($_POST['address'])."',
phone = '".mysql_real_escape_string($_POST['phone'])."',
email = '".mysql_real_escape_string($_POST['email'])."'
WHERE customer_id='".mysql_real_escape_string($_POST['customer_id'])."'");
$update = $mysqli->query($sql);
echo "Customer updated: ";
echo "<a href=customers.php?id=" . $_POST['customer_id'] . ">";
echo "Back to Edit Customer</a>";
?>
</div>
<?php include 'footer.html' ?>
And when I echo the MYSQL query, I get:
UPDATE customer SET name = 'Kellyassdsa', address = 'ads', phone = '0260123123', email = 'asdasd' WHERE customer_id='1'
Which works when I put it in PHPMyAdmin.
I know it'll be some boneheaded little mistake, but I've been trying to get this work for ages now. Any ideas?
Maybe your program just can't connect to your MySQL database.
$customer_results = mysql_query($customer_query, $conn);
I can't see where you gave a value to the var $conn.
If the problem is connection problem then we might need your database info like the name of your table in PhpMyAdmin.
your problem is...
$sql = mysql_query(..);
$update = $mysqli->query($sql);
it should be
$sql = 'UPDATE ...';
$update = $mysqli->query($sql);
i think problem occurs due to line break. pleas make a query in single line without line break.
$sql = mysql_query("UPDATE customer SET name = '".mysql_real_escape_string($_POST['name'])."',address = '".mysql_real_escape_string($_POST['address'])."', phone = '".mysql_real_escape_string($_POST['phone'])."', email = '".mysql_real_escape_string($_POST['email'])."' WHERE customer_id='".mysql_real_escape_string($_POST['customer_id'])."'");
Hope this helps..

PHP: populated fields and database insert

i have Form what populate fields from database, can you show me php to insert data to database, each score to own row in database (id,name,score)
Updated: whit theis codes it prints like this:
lines updated to database: 7 - James - 15
lines updated to database: 7 - James - 15
lines updated to database: 7 - James - 15
now i use this form:
<form action="insert_action2.php" id="form2" title="form2" method="post">
<table>
<?php
$link = mysqli_connect("localhost", "form", "form", "form");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM form2" ;
$players = $link->query($sql);
while($player = $players->fetch_assoc()){
?>
<tr>
<td>
<input type="text" name="id" id="id" value="<?php echo $player["id"]; ?>">
<input type="text" name="name" id="name" value="<?php echo $player["name"]; ?>">
</td>
<td>
<input type="text" name="score" id="score" size="2" value="<?php echo $player["score"]; ?>">
</td>
</p>
<?php
}
$link->close();
?>
</tr>
</table>
<input type="submit" value="update scores">
</form>
insert to database -insert_action2.php
i have tried couple arrays and foreach but cant get those working right...
<?php
foreach($_POST as $players => $value) {
$id = mysqli_real_escape_string($link, $_POST['id']);
$name = mysqli_real_escape_string($link, $_POST['name']);
$score = mysqli_real_escape_string($link, $_POST['score']);
$sql = "UPDATE form2 SET score='$score', name='$name' WHERE id=$id";
if(mysqli_query($link, $sql)){
echo "lines updated to database: <br>$id - $name - $score <br><br><p><p>";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
mysqli_close($link);
?>
You'll need to use:
$sql = "insert into `form2`(`name`, `score`) VALUES ('{$name}', '{$score}')";
When you use some variable inside a string, you need to scape the variable.
Or use this way:
$sql = "insert into `form2`(`name`, `score`) VALUES ('" . $name . "', '" . $score . "')";

Search User Specific information

New to PHP so please be specific.
Once my user logs in they come to a form to submit data.
I would like the user to be able to search for all data entered about them in the past month. From which they could edit or delete if they wish.
What code do I use for this search please. Below is what I have (search not working at all)
<h1>Welcome!</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
Search: <input type="text" name="search">
<input type="submit" value="submit">
</form>
<?php
// Check if the form value
// was submitted, if not
// assign a default value
if(isset($_GET['search'])){
$s = $_GET['search'];
}else{
$s = "%";
}
//echo $s;
// Connects to the database
mysql_connect("localhost","sample","qwerty") or die("Error " . mysqli_error($link));
// Selects which of the databases to use
mysql_select_db('crm');
// Create and runs the query
$sql = "SELECT * FROM hours WHERE employee_id LIKE 'RHilfi'";
//echo $sql;
$results = mysql_query($sql);
echo "<br /><br />";
// Loops though all of the results
while($results_array = mysql_fetch_array($results)){
/*
echo "<pre>";
print_r($results_array);
echo "</pre>";
*/
//print_r($results_array);
echo " Employee ID: " . $results_array['employee_id'] . " , Date: " . $results_array['date'] . " , Rate of Pay: " . $results_array['rate_of_pay'] . " , Hours: " . $results_array['hours'] ." , Amount Due: " . $results_array['amount_due']. " [ EDIT]";
/*
// USE THIS ONE
echo $results_array['title'] . " by " . $results_array['director'] . " [ EDIT]";
*/
echo "<br />";
}
?>
<h1>Submit New Claim</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
Employee ID: <input type="text" name="employee_id">
<br />
Date (yyyy/mm/dd): <input type="text" name="date">
<br />
Rate of Pay: <input type="text" name="rate_of_pay">
<br />
Hours: <input type="text" name="hours">
<br />
Amount Due: <input type="text" name="amount_due">
<br />
<input type="submit" value="Submit">
</form>
<?php
if(isset($_GET['employee_id'])){
$employee_id = $_GET['employee_id'];
$date = $_GET['date'];
$rate_of_pay = $_GET['rate_of_pay'];
$hours = $_GET['hours'];
$amount_due = $_GET['amount_due'];
}else{
$employee_id = "";
$date = "";
$rate_of_pay = "";
$hours = "";
$amount_due = "";
}
if(isset($_GET['employee_id'])){
//echo "INSERT NEW RECORD";
// INSERT NEW RECORD
// Connects to the database
mysql_connect("localhost","sample","qwerty") or die("Error " . mysqli_error($link));
// Selects which of the databases to use
mysql_select_db('crm');
// Create and runs the query
// INSERT INTO `sample`.`dvd` (`dvd_id`, `title`, `year`, `director`) VALUES (NULL, 'title', '1234', 'director');
//$sql = "INSERT INTO crm . 'hours' (employee_id, date, rate_of_pay, hours, amount_due) VALUES (NULL, '$employee_id', '$date', '$rate_of_pay', '$hours', $amount_due)";
$sql = "INSERT INTO hours (ID, employee_id, date, rate_of_pay, hours, amount_due) VALUES (NULL, '$employee_id', '$date', '$rate_of_pay', '$hours', $amount_due)";
//echo $sql;
$results = mysql_query($sql);
echo "<br /><br />";
// OPTIONAL
if(mysql_affected_rows() >= 1){
echo "<h3>Thank you! You have successfully submitted a claim </h3>";
}
}
?>
Log Out
Use mysqli instead and if you're using LIKE in MySQL make it looks like this:
$sql = "SELECT * FROM hours WHERE employee_id LIKE '%RHilfi%'";

Can't get php mysqli while statement to post

I'm new to php and I've been trying to get a form to post to values to a database.
I've successfully connected to the database, because I can pull values from the table and display them in the HTML.
I believe the mysqli_query is correct because I can replace the $variables with examples and they work and do post.
However, I can't seem to find the correct combination of how to insert the $name and $desc variables I've tried $name, '$name', and '$_POST[friendname]. What am I missing?
<?php
include 'includes/connect.php';
$name = $_POST[friendname];
$desc = $_POST[desc];
//WRITE TO DATABASE
if(!$_POST) {
echo "Form info: " . $name . " " . $desc;
echo "<br />Use the form below to add a new person! <br /><br />";
}
else {
$query = "INSERT INTO Friends (ID, Name, Description) VALUES ('NULL', $name, $desc)";
mysqli_query($sql, $query);
echo "<br />You've added " . $name . "<br /><br />";
}
$result = mysqli_query($sql,"SELECT * FROM Friends");
while($row = mysqli_fetch_array($result)) {
echo "<strong>" . $row['Name'] . "</strong> - " . $row['Description'];
echo "<br>";
}
?>
<p><strong>Add a new person to the database</strong></p>
<!-- FORM -->
<form name="addform" action="index.php" method="post">
Name: <input type="text" name="friendname" /><br />
Description: <input type="text" name="desc" /><br />
<input type="submit" name="submit" label="submit" />
</form>
try not to put the id into the query, I assume that this column is auto-increment.
Also you should put the variables as show below
$query = "INSERT INTO Friends (Name, Description)
VALUES ('".$name."', '".$desc."')";
NOTE: If you can show us what data is storing in your database it would be of help
try to replace
$query = "INSERT INTO Friends (ID, Name, Description)
VALUES ('NULL', $name, $desc)";
to
$query = "INSERT INTO Friends (ID, Name, Description)
VALUES ('NULL', {$name}, {$desc})";
instead of write SQL statement as string,you can use PDO
I've had to wrap the desc in backquotes which is MySQL-speak for "this is a variable name" because desc is a keyword. You will make your life easier if you change the column name to description instead.
PDO comes as standard on most PHP installations and does make things a lot easier.
<?php
$pdo = new PDO("mysql:host=localhost;dbname=mysql", "user", "password");
if (isset($_POST))
{
$name = $_POST['friendname'];
$desc = $_POST['desc'];
echo "Form info: " . $name . " " . $desc;
// WRITE TO DATABASE
$sql = "INSERT INTO Friends(friendname, `desc`) VALUES (:fn, :d)";
$query = $pdo->prepare($sql);
$query->execute(array(':fn'=>$name, ':d'=>$desc));
echo "<br />You've added " . $name . "<br /><br />";
die;
}
?>
<p>Use the form below to add a new person!</p>
<p><strong>Add a new person to the database</strong></p>
<form name="addform" action="index.php" method="post">
Name: <input type="text" name="friendname" /><br />
Description: <input type="text" name="desc" /><br />
<input type="submit" name="submit" label="submit" />
</form>
There is a reasonable example of executing a "SELECT *" here:
How to fetch row with PDO

I can't figure out why one of these PHP scripts is not working

I have two scripts doing almost the same things but one of them is not working. I just can't figure where is the problem. Both scripts have almost the same code but the "update message" script is not working. I do not get any php error but the database is not updating.
Delete script (working) :
<?php
function deleterow()
{
$con=mysqli_connect("localhost","root","root","TP1AlexandreBouletCouture");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$delete_id = ($_GET["delete_id"]);
$sql="DELETE FROM `table1` WHERE `table1`.`id` = '$delete_id'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo '<p>Message supprimé</p>';
mysqli_close($con);
}
if(isset($_GET['delete_id']))
{
deleterow($_GET['delete_id']);
}
?>
<form action="history.php" method="get">
<input type="submit" value="Supprimer">
<input type="hidden" name="delete_id" value='.$row['id'].'>
</form>
Update message script (not working) :
<?php
function updatemyinfos()
{
$con=mysqli_connect("localhost","root","root","TP1AlexandreBouletCouture");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$update_id = ($_GET["update_id"]);
$new_message = ($_GET["updatemessage"]);
$sql="UPDATE `table1` SET `message` = '$new_message' WHERE `table1`.`id` ='$update_id";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo '<p>Message modifié</p>';
mysqli_close($con);
}
if(isset($GET['updatemessage']))
{
updatemyinfos($GET['updatemessage']);
}
?>
<form action="history.php" method="get">
<textarea style="resize:none"cols="35"rows="3"name="updatemessage">'.$row['message'].'</textarea>
<input type="submit" value="Modifier">
<input type="hidden" name="update_id" value='.$row['id'].'>
</form>
You're missing a quote after $update_id.
'$new_message' WHERE `table1`.`id` ='$update_id
But you should use PDO, http://php.net/manual/en/book.pdo.php. The mysql extension was deprecated from php 5.5.0
in addition to Cristian's answer, your php variables in the form HTML won't get parsed. You need to wrap them in php tags:
<input type="hidden" name="update_id" value="<?php echo $row['id']; ?>">

Categories