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%'";
Related
Once again I am at the mercy of your knowledge and hope you can help.
Actual question is the bold italics, however you won't be able to help without reading the information that I've given.
Background to Question - I'm creating a photography website (for my mum) using HTML, CSS, MySQL and PHP. I'm in the process of working on the database, specifically on allowing my mum to insert images into the database using this form (http://i.imgur.com/h4nXFFA.png). She has no idea how to code, therefore I need to make it easy for her.
Database Background (what you need to know) - I've got an image_tbl and album_tbl. The album_tbl is shown here - http://i.imgur.com/4GXh9MP.png - with each album having an ID and Name (forget the 'hidden'). The image_tbl is shown here - http://i.imgur.com/RgC35Nd.png - with the important part (for this question) being the albumName.
Aim - I've managed to populate the 'Insert a New Image' form with the albums from album_tbl (picture shows 'Exploration'). I want her to be able to click the AlbumName (so she knows what album to add to), yet I want the image she inserts to receive the albumID in the database. Here's a Pastebin of my code thus far.
http://pastebin.com/6v8kvbGH = The HTML Form, for helping me be aware of the 1st Form in the code...
http://pastebin.com/4X6abTey = PHP/MySQL Code. Here we have me calling the inputs in the form and using them in 2 SQL Queries. The first Query is aiming to get the albumID of the albumName that was entered, and this is where it goes wrong. The commented out statements (using //) are me error-checking, and albumName is passed on from the form. However, the number of rows returned from the 1st SQL Statement is 0, when it should be 1. This is where I need help as clearly something's wrong with my assoc array ...
2nd Aim - Once the 1st SQL Query is working, the 2nd SQL Query is hopefully going to input the required variables into image_tbl including the albumID I hopefully just got from the 1st SQL Query.
I hope this is all that's required, as far as I'm aware the people who understand this should be able to help with what I've given. Thanks very much in advance!
Jake
Someone asked me to paste the code - HTML Form:
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['albumName'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
Inserting the image using PHP/MySQL:
<?php
$username="root";
$password="";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumName = $_POST['albumName'];
// echo "album name is" . $albumName;
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
$albumID = $conn->query($sql);
// echo "Number of rows is " . $albumID->num_rows;
if ($albumID->num_rows > 0) {
// output data of each row
while($row = $albumID->fetch_assoc()) {
echo "Album ID: " . $row["albumID"]. "<br>";
}
} else {
echo "0 results";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
This line:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
should be:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = '$albumName'";
since the album name is a string.
You should check for errors when you perform a query:
$albumID = $conn->query($sql) or die($conn->error);
You can't use $albumID in the INSERT query. Despite the name of the variable, it doesn't contain an album ID, it contains a mysqli_result object that represents the entire resultset of the query -- you can only use it with methods like num_rows and fetch_assoc() to extract information from the resultset.
What you can do is use a SELECT statement as the source of data in an UPDATE:
$stmt = $conn->prepare("INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT ?, ?, ?, ?, ?, ?, albumID
FROM album_tbl
WHERE albumName = ?";
$stmt->bind_param("sssssss", $name, $dateTime, $caption, $comment, $slideshow, $hidden, $albumName);
$stmt->execute();
Note that when you use a prepared query, you don't need to fix the quotes in $comment (which you should have done using $conn->real_escape_string($comment), not str_replace()).
Just to help you understand, this can also be done without a prepared query.
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT '$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', albumID
FROM album_tbl
WHERE albumName = '$albumName'";
First of all create a single database connection let say
db_connection.php
<?php
$username="root";
$password="1k9i2n8gjd";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
Then in your form or any php file that needs database connection you can just include the db_connection.php so that you have one database connection.
Note: I have change the value of option to albumId so that you dont need to query or select based on albumName because you already have the albumID passed in imagesInsert.php via $_POST
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
?>
<html>
<head>
<title>Admin Page | Alison Ryde's Photography</title>
<link rel="stylesheet" type="text/css" href="../../css/style.css">
</head>
<body>
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = $conn->query($sql);// mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['albumID'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
</html>
Then in your php code that inserts the data should be like this.
imagesInsert.php
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
Another piece of advice is to use prepared statementif your query is build by users input to avoid sql injection
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $name, $dateTime, $caption,$new_comment,$slideshow,$hidden,$albumID);
$stmt->execute();
hope that helps :) good luck
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..
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 . "')";
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.
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