POST Data not inserting into sql table - php

I am using a form. (I wanted the message text as a text area but changed back to normal text to see if this was the problem)
This is the form I am using
<form name="addmessage" method="POST" action="addmessage.php" >
<input type="text" name="message_title" id="message_title">Message Title</input>
<input type="text" name="message_text" id="message_text">Message</input>
<input type="submit" name="submit" value = Add>
</form>
Below is the PHP code. I understand i need to protect against sql injection however, i can do this later.
<?php
include_once("config.php");
if(isset($_POST["message_title"]) && strlen($_POST["message_title"])>0)
{
$message_title=$_POST['message_title'];
$message_text=$_POST['message_text'];
session_start();
$barber_id = $_SESSION['barber_id'];
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
}
else
{
//Output error
header('HTTP/1.1 500 Error You have left it blank');
exit();
}
header("location:messages.php");
?>
If manually enter data using phpMyAdmin, I can get it to display using the code below.
include_once("config.php");
session_start();
$barber_id = $_SESSION['barber_id'];
$results = $mysqli->query("SELECT * FROM messages WHERE barber_id ='$barber_id' ");
//get all records from table
while($row = $results->fetch_assoc())
{
$prices_id = $row['prices_id'];
echo '<div data-role="collapsible">';
echo '<h1>';
echo ' Message Title: ';
echo $row['message_title'];
echo '</a>';
echo '</h1>';
echo '<p>';
echo $row['message_text'];
echo ' Delete</div>';
}
$mysqli->close();
?>

At $insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
you should write
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."','".$message_text."')");
Everytime you pass a String or other non int values you must pass them like that: 'xx', otherwise mysql will see it as query param and it crashes.

Related

PHP code inserts into sql db with text box inputs but not with select options (dropdowns)

Through hours of research and looking through code in questions submitted on this site, I was finally able to get the select options (dropdowns) to pull data from my database tables into the dropdown lists on my html form.
However, my issue is that when the fields on the form were inputs they inserted the new information into the database just fine. Unfortunately, now that I've implemented the dropdown lists as part of the form, none of the information from the form inserts into the database anymore. Clicking on the 'submit' button returns the response that it was successful, but when I check the table in the database, the new information is not there.
I'm sorry I haven't been able to figure this piece of functionality out by myself. I noticed my last question received negative feedback, so I'm leary to even submit this one, but I really need some help.
Will you please look through the following code and let me know what I'm missing or have coded incorrectly? I just need to know what I need to do to make the selected values from the dropdown lists insert into the 'dvd' table and 'categoryname' and 'genretype' fields, respectively.
<?php
session_start();
//include the header
include ('../main/header.php');
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {
require_once ('../../../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize error array.
// Check for a first name.
if (empty($_POST['title'])) {
$errors[] = 'You forgot to enter a title.';
} else {
$title = mysqli_real_escape_string($dbc, $_POST['title']);
}
// Check for a category.
if (empty($_POST['numavail'])) {
$errors[] = 'You forgot to enter quantity purchased.';
} else {
$numavail = mysqli_real_escape_string($dbc, $_POST['numavail']);
}
// Check for a category.
if (empty($_POST['categoryname'])) {
$errors[] = 'You forgot to enter a category.';
} else {
$categoryname = mysqli_real_escape_string($dbc, $_POST['categoryname']);
}
// Check for a genre.
if (empty($_POST['genretype'])) {
$errors[] = 'You forgot to enter a genre.';
} else {
$genretype = mysqli_real_escape_string($dbc, $_POST['genretype']);
}
if (empty($errors)) { // If everything's OK.
// Add the movie to the database.
// Check for existing record.
$query = "SELECT id FROM dvd WHERE title='$title'";
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
if ($result) { // If it ran OK.
echo "<p><b>Success! The new movie has been added.</b></p>";
echo ('<p><div style="margin-top:30px;">');
echo ('<span style="float:left;">');
echo ('<FORM METHOD="LINK" ACTION="../dvd/index.php"><INPUT TYPE="submit" VALUE="Back to DVDs" STYLE="margin:0px 15px 0px 0px;"></form></span></div></p>');
echo ('<br style="clear:both;"></br>');
exit();
} else { // If it did not run OK.
$errors[] = 'The movie could not be added due to a system error. We apologize for any inconvenience.'; // Public message.
$errors[] = mysqli_error($dbc); // MySQL error message.
}
} else { // Title is already taken.
$errors[] = 'The movie title entered already exists.';
}
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} else { // Form has not been submitted.
$errors = NULL;
} // End of the main Submit conditional.
// Begin the page now.
if (!empty($errors)) { // Print any error messages.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo "$msg<br />";
}
echo '</p>';
echo '<p style="color:red; font-weight:bold;"><em>Please try again.</em></p></br>';
}
// Create the form.
?>
<h1>Add a Movie</h1>
<h2>Please complete all of the fields below:</h2>
<form action="../dvd/add.php" method="post">
<p>Title: <input type="text" name="title" size="15" maxlength="15" value="<?php echo $_POST['title']; ?>"></p>
<p>Quantity Purchased: <input type="text" name="numavail" size="15" maxlength="30" value="<?php echo $_POST['numavail']; ?>"></p>
<p>
<?php
include ('../../../mysqli_connect.php'); // Connect to the db.
$ddlquery = "SELECT categoryname FROM category ORDER BY categoryname ASC";
$ddlresult = mysqli_query($dbc, $ddlquery) or die("Bad SQL: $ddlquery");
echo 'Category: <select name="categoryname" size="1">';
while($ddlrow=mysqli_fetch_array($ddlresult, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow['categoryname']."'>" . $ddlrow['categoryname'] . "</option>";
}
echo "</select>";
?>
<p>
<?php
$ddlquery2 = "SELECT genretype FROM genre ORDER BY genretype ASC";
$ddlresult2 = mysqli_query($dbc, $ddlquery2) or die("Bad SQL: $ddlquery");
echo 'Genre: <select name="genretype" size="1">';
while($ddlrow2=mysqli_fetch_array($ddlresult2, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow2['genretype']."'>" . $ddlrow2['genretype'] . "</option>";
}
echo "</select>";
?>
<p>
<input type="submit" name="submit" value="Submit">
<input type=reset value=Reset>
<input type="hidden" name="submitted" value="TRUE"></p>
</form>
<?php
// Include footer.php
include("../../includes/footer.php");
?>
You forgot to actually run the insert into database
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
$result = mysqli_query($dbc, $query); // <---- ADD HERE
if ($result) { // If it ran OK.
....

storing text in different rows of MySQL database based on newline

The HTML code is below:
<div class="form-data">
<form method="POST" action="test_upload_file.php" enctype="multipart/form-data">
ID:<br>
<input type="text" name="id"><br>
Quote:<br>
<textarea rows="4" cols="30" name="text-file"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
The corresponding php code is below:
<?php
//connect database
$conn = mysqli_connect("localhost","root","","androidtest");
if (isset($_POST['submit'])) {
$quote_id = $_POST['id'];
$text = $_POST['text-file'];
//insert data
$sql = "INSERT INTO quotes (quote_id, quote) VALUES ('$quote_id', '$text')";
//store in the table
$insert = mysqli_query($conn, $sql);
if ($insert) {
echo "Success.";
} else {
echo "Error.";
}
//close mysql connection
mysql_close($conn);
//won't resubmit the form
header("Location: " . $_SERVER['REQUEST_URI']);
}
?>
I want to post multiple sentences separated by break in textarea. They should be stored in different rows in MySQL database.
For eg, if i put an id of 2 and post a text having multiple sentences separated by break or newline, then it should store in the database like this:
quote_id quote
2 line 1
2 line 2
2 line 3
Try following code, it may help you. I am not sure the textarea next line seperated by '\n'. Please make sure that
//connect database
$conn = mysqli_connect("localhost","root","","androidtest");
if (isset($_POST['submit'])) {
$quote_id = $_POST['id'];
$get_file = $_POST['text-file'];
$textArray = explode("\n", $get_file);
foreach($textArray as $key=>$value) {
//insert data
$sql = "INSERT INTO quotes (quote_id, quote) VALUES ('$quote_id', '$value')";
//store in the table
$insert = mysqli_query($conn, $sql);
if ($insert) {
echo "Success.";
} else {
echo "Error.";
}
}
//close mysql connection
mysql_close($conn);
//won't resubmit the form
header("Location: " . $_SERVER['REQUEST_URI']);
}

Add 'delete' button to php results table

I outputted the results of a MySQL table to an HTML table, I'm trying to add a Delete button to remove the user but it doesn't work.
HTML form code:
<?php
$response = $bdd->query('SELECT * FROM users');
$i = 1;
while ($datas = $response->fetch()) {
?>
<tr>
<td><?php echo $datas['first_name']; ?></td>
<td><?php echo $datas['last_name']; ?></td>
<td>
<form action="_delete.php?id=<?php echo $datas['id']; ?>" method="post">
<input type="hidden" name="name" value="<?php echo $datas['id'];?>">
<input class="btn btn-danger" type="submit" name="submit" value="X">
</form>
</td>
</tr>
And this is my _delete.php :
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'root', 'root');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
?>
<?php
$id = (int)$_GET['id'];
$query = "DELETE FROM users WHERE id={$id} LIMIT 1";
//sends the query
mysql_query ($query);
if (mysql_affected_rows() == 1) {
?>
<strong>User Has Been Deleted</strong>
<?php
} else {
?>
<strong>Deletion Failed</strong>
<?php
}
?>
My result url is good /_delete.php?id=13 but Delete script isn't.
I have this error: Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the future
Any idea?
Your messing around with GET and POST params. You defined a get param named id containing your id and a post param named name containing also your id.
But currently you are trying to access the get param with $_POST (which contains only post params).
To solve your problem, you should use $_GET['id'] or $_POST['name'].
In each way, keep in mind to protect you input from sql injections. Currently the user could pass anything else as well. A simple cast to an int, would be enough.
$id = (int)$_GET['id'];
$query = "DELETE FROM users WHERE id={$id} LIMIT 1";
I have incoporated a few suggestions in my answer, try and see if it works.
Create a connection, then get the ID using $_GET instead of $_POST.
<?php
$con=mysqli_connect("localhost","dbuser","dbpassword","dbname");
if($con==false){
die("ERROR:Could not connect.". mysqli_connect_error());
}
else{
$id=$_GET['id']
$query = "DELETE FROM users WHERE id='$id' LIMIT 1";
//sends the query
mysql_query ($con,$query);
if (mysql_affected_rows() == 1) {
?>
<strong>User Has Been Deleted</strong>
<?php
} else {
?>
<strong>Deletion Failed</strong>
<?php
}
}
?>

If there is no $_POST present after a URL, how can I prevent (nothing) from getting passed into a MySQL query, and causing an error?

I have a Delete.php page that deletes records based on their ID.
When there is an ID, i.e., Delete.php?id=3610, all is well, and it functions as expected.
If I just go to "Delete.php" and that's it - no ID, it generates:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1"
From the little I understand, it is doing this because I am trying to pass a nonexistent variable into my query.
I have been trying to put if (empty($_POST['id'])) { } in different places, which removes the error, but breaks something else.
Here is my code:
<?php
require_once 'functions.php';
$conn = mysqli_connect("localhost", "user", "pass",'db');
writeHead("Delete Track");
if (isset($_POST['delete'])) {
$trkid = $_POST['trkid'];
$query = "DELETE FROM track WHERE TrackID=$trkid";
mysqli_query($conn, $query) or die(mysqli_error($conn));
if (mysqli_affected_rows($conn)>0) {
header("Location: Display.php?action=deleted&id=$trkid&status=deleted");
exit();
}
echo "<p class='error'>Unable to update record</p>";
} else {
if (!isset($_GET['id'])) {
echo "<p class='error'>No Track ID provided.<br><a href='Display.php'>Return to display page.</a><p>";
}
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}
?>
<p>Track Information:</p>
<p><?php echo "<b>ID: $trkid <br>Title: $Name</b>"; ?></p>
<form method="post" action="Comp3Delete.php">
<p>
<input type="hidden" name="trkid" value="<?php echo $trkid; ?>">
<input type="submit" name="delete" class="btn" value="Confirm Delete">
</p>
</form>
<p>Return to Track Table Display</p>
<?php writeFoot(); ?>
Your post code is fine. it's the GET code that's wrong:
if (!isset($_GET['id'])) {
^^^^^^^^--check if the parameter exists
}
$trkid=$_GET['id'];
^---try to use the parameter ANYWAYS, even if it doesn't exist.
$trkid=$_GET['id']; has no condition so it runs even when no id is passed which generates the error. Your code should go like this:
if(isset($_GET['id'])){
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}

I can't get my update query to work (php / mysqli)

I am posting a shortened version of the form and updating lines. I will truly appreciate any help. I have spent the last 48 hours trying all I could think of and it's driving me insane. If I remove the line if($_SERVER["REQUEST_METHOD"]=="POST"), the program runs on loading the page and does update the table at the ID in the url with a blank field. Thanks in advance. Here's the code:
<?php
$id = $_GET['id'];
$user = $_SESSION['user'];
Echo '<form action="editone.php" method="POST">
Enter new name:<input type="text" name="namex" />
<input type="submit" name="Submit" value="Update List" /> </form>';
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $id);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>
I think your form action didn't pass id.
<form action="editone.php" method="POST">
If you're using this single file as form editor and action, your form editor URL should be http://localhost/editone.php?id=1
Try to change your form action to
<form action="editone.php?id='.$_GET['id'].'" method="POST">
or just leave the action blank
<form action="" method="POST">
Ok - maybe I'm way off base here but I see the following problems.
1) Your method is POST however your id is coming from GET.
2) I don't see where the id is coming from. It could be coming from somewhere and not posted but I don't see it.
Have you checked to verify the value is actually being passed through to the php?
try this
echo "GET = " . var_dump($_GET);
echo "<br><br>";
echo "POST = " . var_dump($_POST);
exit();
Post the results and then post where the id is coming from if you can't figure it out still. :)
Use the below code:
$query = "SELECT now_edit, FROM EDITORIES WHERE edit_id='$numb' LIMIT 1";
I assume your page is being called initially from an anchor link on another page which is why you are getting the id from $_GET['id'].
When the user presses the submit button of course the form is being submitted as a POST so all the data will be in $_POST, therefore $_GET['id'] will fail and should be generating an error message.
You need to save the $_GET['id'] from the first instantiation so you can use it when the form is posted to you. So put it in a hidden field that will be posted to you with the post
<?php
session_start();
$user = $_SESSION['user'];
if($_SERVER["REQUEST_METHOD"]=="GET") {
if ( isset($_GET['id']) ) {
$id = $_GET['id']);
} else {
// no param passed, could be a hack
header('Location: some_error_page.php');
exit;
}
echo '<form action="editone.php" method="POST">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo 'Enter new name:<input type="text" name="namex" />';
echo '<input type="submit" name="Submit" value="Update List" /></form>';
}
if($_SERVER["REQUEST_METHOD"]=="POST") {
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $_POST['id']);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>

Categories