Can someone please help me understand, why my code is not inserting data into my database from this form? I can get it to Select and Echo the same info from the same database to the page but when I go to add new data through the form it never makes it to the db.
I'm not getting any errors at all and I have error reporting set at the top of my page. I even set a javascript alert to capture the values of the input when clicking the submit button and they return the true values. They just won't insert into the database.
What am I doing wrong here?
<?php
if(isset($_POST['addContent'])) {
$addTitle = $_POST['title'];
$addEntry = $_POST['entry'];
$sql = mysqli_query($conn, "INSERT INTO `basic` (`title, entry`) VALUES ('$addTitle', '$addEntry')") or die(mysqli_error($conn));
$result = mysqli_query($sql);
if(!$result) {
echo mysql_error($sql);
}
}
?>
<!-- Modal -->
<div class="modal fade" id="addContentModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add Data</h4>
</div>
<div class="modal-body">
<form method="POST" action="">
<input type="hidden" name="addContent" id="addContent" value="1">
<div class="form-group">
<label for="title">Title</label>
<input id="addTitle" name="addTitle" type="text" class="form-control">
</div>
<div class="form-group">
<label for="entry">Entry</label>
<textarea id="addEntry" name="addEntry" class="form-control" ></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="saveAddBtn" class="btn btn-primary" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
UPDATE:
Ok so here's my attempt at addressing some of the issues you all have enlightened me to. Still same result...any other ideas?
<?php
if(isset($_POST['addContent'])) {
$addTitle = $_POST['title'];
$addEntry = $_POST['entry'];
if($addTitle != "" && $addEntry != "")
{
$sql = $conn->prepare("INSERT INTO basic VALUES ('',?,?)");
$sql->bind_param('sss', $addTitle, $addEntry);
$result = mysqli_query($sql);
if(!$result) {
echo mysqli_error($sql);
}
}
}
?>
<!-- Modal -->
<div class="modal fade" id="addContentModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add Data</h4>
</div>
<div class="modal-body">
<form method="POST" action="">
<input type="hidden" name="addContent" id="addContent" value="1">
<div class="form-group">
<label for="title">Title</label>
<input id="addTitle" name="title" type="text" class="form-control">
</div>
<div class="form-group">
<label for="entry">Entry</label>
<textarea id="addEntry" name="entry" class="form-control" ></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" id="saveAddBtn" class="btn btn-primary" data-dismiss="modal" value="Save changes">
</div>
</div>
</div>
</div>
The problem are these lines:
$sql = mysqli_query($conn, "INSERT INTO `basic` (`title`, `entry`) VALUES ('$addTitle', '$addEntry')") or die(mysqli_error($conn));
$result = mysqli_query($sql);
Remove the first mysqli_query and set $sql to equal just the string, this will give you the result and not the result of the result (it'll return boolean false when using the result as a query) and also, backtick each column name singularly, not as a whole :)
change your query to:
$sql = mysqli_query($conn, "INSERT INTO `basic` (`title`, `entry`) VALUES ('$addTitle', '$addEntry')") or die(mysqli_error($conn));
The backticks are affecting the query. Note that the back ticks are around each column individualy not around all of them. The way you have it would suggest you have a column called title, entry. You should also remove the $result line because the query has been executed already. Now you also have to change the if statement to if (! $sql).
Update
<?php
if(isset($_POST['addContent'])) {
$addTitle = $conn->real_escape_string($_POST['title']);
$addEntry = $conn->real_escape_string($_POST['entry']);
if(!empty($addTitle) && !empty($addEntry)) // There is a function for this
{
// Because you are only inserting 2 values there only need to be 2 `?` and 2 parameters
$sql = $conn->prepare("INSERT INTO `basic` (`title`, `entry`) VALUES (?,?)"); // Added column names just to be sure values are inserted on correct columns
$sql->bind_param('ss', $addTitle, $addEntry); // Note the 2 "s" not 3
$sql->execute();
if($sql->affected_rows < 1 ) {
echo $sql->error(); // Don't know for shure what this should be `error` or `error()`
}
}
}
?>
I can't believe none of us caught this sooner. But my submit button was not even inside the form tag! My buddy pointed this out and it fixed the issue. Thanks for trying everyone!
change your query to:
$sql = mysqli_query($conn, "INSERT INTO `basic` (title, entry) VALUES ('$addTitle', '$addEntry')") or die(mysqli_error($conn));
The backticks are affecting the query.
Related
My problem is I am trying to call the PHP file while clicking the button on my bootstrap but it is not working for me here by I paste my code of bootstrap and PHP kindly guide me for the solution
Thanks in advance
I am tired of changing button to form and all of these but not working I am working on PHP 7 and Bootstrap 4
<?php include "includes/db.php"; ?>
<?php
// echo "<h1> Testing </h1>";
// $db = mysql_select_db("cateory", $connection); // Selecting Database from Server
function(){
if (isset($POST['submit'])){
// $connect=mysqli_query($connection,)
$cat_title=$POST['cat_title'];
if($cat_title==""||empty($cat_title)){
echo "The field should not empty";
}
else{
$query="INSERT INTO category (cat_title)";
$query .=" VALUE ('{$cat_title}')";
$create_category_query = mysqli_query ($connection,$query);
if(!$create_category_query){
die ('QUERY FAILED'.mysqli_error($connection));
}
}
}
}
?>```
<!-- ADD CATEGORY MODAL -->
<div class="modal fade" id="addCategoryModal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-success text-white">
<h5 class="modal-title">Add Category</h5>
<button class="close" data-dismiss="modal">
<span>×</span>
</button>
</div>
<div class="modal-body">
<form action="" method="post">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
</div>
</div>
<div class="modal-footer">
<?php insert_categories(); ?>
<button class="btn btn-success" type="submit" data-dismiss="modal">Save Changes</button>```
</div>
</form>
</div>
</div>
Do change your code like:
<?php
if ( isset( $_POST['submit']) ) {
// $connect=mysqli_query($connection,)
$cat_title = $_POST['cat_title'];
if($cat_title==""||empty($cat_title)){
echo "The field should not empty";
} else {
$query="INSERT INTO category (cat_title)";
$query .= " VALUE ('{$cat_title}')";
$create_category_query = mysqli_query ($connection,$query);
if(!$create_category_query){
die ('QUERY FAILED'.mysqli_error($connection));
}
}
}
?>
<!-- ADD CATEGORY MODAL -->
<div class="modal fade" id="addCategoryModal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-success text-white">
<h5 class="modal-title">Add Category</h5>
<button class="close" data-dismiss="modal">
<span>×</span>
</button>
</div>
<div class="modal-body">
<form action="" method="post">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="cat_title">
</div>
<div class="modal-footer">
<?php insert_categories(); ?>
<button class="btn btn-success" type="submit" data-dismiss="modal">Save Changes</button>```
</div>
</form>
</div>
</div>
</div>
</div>
Problems with your code:
Your HTML formatting itself is wrong. you have broken your form tag with div of modal-body. You have to reconsider your HTML design.
No need to wrap PHP code in a function with no name.
You just have to use the code only.
You have named your input as title while saving/checking data as cat_title.
Check your whole codebase again.
its me again :)
i'm almost done with my project theres only one more thing left.
i am not able to update values in my database using pdo.
this is my script
<a
href="?UpdateUser=' .$ID. '"
class="btn btn-sm btn-icon btn-pure btn-default on-default edit-row"
data-original-title="Bearbeiten"
ref="" data-toggle="modal" data-target="#EditUser">
<i class="icon wb-edit" aria-hidden="true"></i></a>
<div class="modal fade" id="EditUser" aria-hidden="false" aria-labelledby="EditUserModal"
role="dialog" tabindex="-1">
<div class="modal-dialog modal-simple modal-center">
<form class="modal-content" method="POST" role="form" action="">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="EditUserModal">Benutzer bearbeiten</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xl-12 form-group">
<p><b>Username</b></p>
<input type="text" class="form-control" name="username" value="'.$username.'">
</div>
<div class="col-xl-4 form-group">
<p><b>Vorname</b></p>
<input type="text" class="form-control" name="vorname" value="'.$vorname.'">
</div>
<div class="col-xl-8 form-group">
<p><b>Nachname</b></p>
<input type="text" class="form-control" name="nachname" value="'.$nachname.'">
</div>
<div class="col-xl-8 form-group">
<p><b>Email</b></p>
<input type="email" class="form-control" name="email" value="'.$email.'">
</div>
<div class="col-xl-4 form-group">
<p><b>TelefonNr.</b></p>
<input type="text" class="form-control" name="handy" value="'.$handy.'">
</div>
<div class="col-xl-12 form-group">
<p><b>Admin</b></p>
<input type="text" class="form-control" name="admin" value="'.$admin.'">
</div>
<div class="col-md-12 float-right">
<button class="btn btn-primary btn-outline" data-dismiss="modal" type="submit">Speichern</button>
</div>
</div>
</div>
</form>
</div>
</div>
</td>
</tr>';
}
if(isset($_POST['UpdateUser']))
{
if($_POST['UpdateUser'])
{
$stmt = $odb->execute("UPDATE Account SET username = '$username' , vorname = '$vorname', nachname = '$nachname', email = '$email', handy = '$handy', admin = '$admin' WHERE id=? ");
}
echo "<meta http-equiv='refresh()' content='0'>";
}
am i doing a wrong query ? or why is it not updating?
there is no error showing up on the page, but the values are not updating nor refreshing the page.
You need to use prepare before execute, like this:
$query = 'UPDATE Account SET
username = :username,
vorname = :vorname,
nachname = :nachname,
email = :email,
handy = :handy,
admin = :admin
WHERE id = :id';
$stmt = $pdo->prepare($query);
$stmt->execute(array(
':username' => $username,
':vorname' => $vorname,
':nachname' => $nachname,
':email' => $email,
':handy' => $handy,
':admin' => $admin,
':id' => $id
));
Also, is better to use placeholders for every input value, instead of write variables inside the query string.
And now I figured out this:
You are using a form to send data with method POST and trying to read $_POST['UpdateUser'] to start executing the update, but in that form there is no field called UpdateUser.
You have to add that value inside the form, or change the if (isset($_POST['UpdateUser'])) with some other field.
i've tried looking at the source code and changing this but still have no luck! Hope someone can spot the mistake i've made.
Im basically just trying to submit a form with just 1 input field for now using AJAX and PHP to post using PDO method.
Here is my code:
Connection to database
<?php
define('HOST', 'localhost');
define('DB_NAME','test');
define('USER','root');
define('PASS','');
$dsn = 'mysql:host='.HOST.'; port='.PORT.'; dbname='.DB_NAME;
try {
$bd = new PDO($dsn, USER, PASS);
// $bd->setAttribute(PDO::ATT_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Problem connecting to database, contact admin';
}
?>
Bootstrap Form
<div class="modal fade" id="add_new_record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add New Record</h4>
</div>
<div class="modal-body">
<div class="form-group">
<form id ="myform">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default" id="submit" value="submit">Submit</button>
</form>
</div>
</div>
</div>
</div>
AJAX Script
$(document).ready(function(){
$('#myform').submit(function(){
var data = $(this).serialize();
$.ajax({
url: "insert.php",
type: "POST",
data: data,
success: function( data )
{
alert( data );
},
error: function(){
alert('ERROR');
}
});
return false;
});
});
insert.php Script
<?php
require_once('config.php');
if(isset($_POST['submit'])){
$name = $_POST['name'];
$sql = 'INSERT INTO people(name) ';
$sql .= ' VALUES (:name)';
try {
$query = $bd->prepare($sql);
$query->bindValue(':name', $name, PDO::PARAM_STR);
if($query->execute()){
echo "recorded added sucessfully";
}else{
echo "Problem adding new record";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
In your html code, you don't have any form. So you can't directly use .submit() or .serialize()
Consider closing you form elements within <form>
Change your html to this:
<div class="modal fade" id="add_new_record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add New Record</h4>
</div>
<div class="modal-body">
<div class="form-group">
<form id ="myform">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Name" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default" id="submit" value="submit">Submit</button>
</form>
</div>
</div>
</div>
</div>
Update:
Add name attribute in input tag.
Serialize labels items by its name attribute.
Try to read about submit() to fully understand how it works: https://api.jquery.com/submit/
You are not using the <form> tag, so submit() doesn't catch any event.
Try wrapping your input and buttons in the same form tag, with id=myform and try again.
Also you are not using event.preventDefault(), without which the page will be refreshed.
I have displayed some values from database in form of a table using php. One column of the table is reserved for edit. I wish that each row of the table can be edited.
Code for edit is
echo"<td class='success'><button class='btn blue' data-toggle='modal' data-target='#myeditModal'>Edit </button></td>";
Code used in modal is
<div class="modal fade" id="myeditModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Edut Treatment</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" action="edit.php?id="$row['id']"" enctype="multipart/form-data" method="post">
<div class="form-group">
<label class="col-lg-4 control-label"> Name</label>
<div class="col-lg-6">
<input class="form-control" value="" type="text" name="name" >
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" value="Save Changes" type="submit" name="submit">
<span></span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Code for edit.php page is
<?php
include('admin_session.php');
$con=mysqli_connect("localhost","root","","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
mysqli_query($con,"UPDATE treatment_type SET name='".$name.'" WHERE id='".$id."'");
mysqli_close($con);
header("Location: abc.php");
?>
My problem is that when I reach the edit.php page I get the url as this: http://example.com/xyz/edit.php?id=
I am not able to carry the id due to which I am not able to edit a specific row of the table.
If you are enable to call the URL just fine. Most likely because of this line on the UPDATE statement:
WHERE id='".$id."'");
^^^^^^^
Second, properly echo the row id:
action="edit.php?id=<?php echo $row['id']; ?>"
And make sure $name is defined.
And why not use prepared statements instead:
if(isset($_GET['id'], $_GET['name'])) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect("localhost","root","","db");
$id = $_GET['id'];
$name = $_GET['name'];
$sql = 'UPDATE treatment_type SET name = ? WHERE id = ?';
$update = $con->prepare($sql);
$update->bind_param('si', $name, $id);
$update->execute();
if($update->affected_rows > 0) {
header("Location: abc.php");
} else {
echo 'did not update';
}
}
The way you have it now, you need to change to this..
<form class="form-horizontal" role="form" action="edit.php?id='<?php echo $row['id'];?>'" enctype="multipart/form-data" method="post">
To output the ID corerectly into the form.
But this way you are ouputting multiple different modal forms for each row??
You should really just display the modal once, then pass the ID via jquery/javascript to the modal, do an ajax request-display the data, and then edit it.
If its just one row, it should be fine, But if you want multiple table rows, with the ability to edit any value in the row, then you definitely need to use ajax/jquery/javascript
Example using one modal window, and passing ID via jquery...
PHP
echo"<td class='success'><button class='btn blue editButton' data-id='<?php echo $row['id'];?>' >Edit </button></td>";
Jquery
$(document).ready(function(){
//Click button, apply id, and open modal.
$('.editButton').click(function(){
var id = $(this).data('id');
//Apply action with id to form
$('#myForm').attr('action','edit.php?id='+id);
//Open modal
$('#myModal').modal({background:'static'});
}):
//If you want values to come into the modal you need to do a sepereate ajax call to get the one particular element from database.
});
I have a Bootstrap template, anyhow I am creating a modal [popup] on my page where the user can submit a form. Although The form works fine but on my PHP code I orignally have that after submitting, it'll show a message either if it worked it would say something like 'Your message has been posted' or if it was an error it would show the error.
But unfortunately once I click 'Post' it posts, but when I click 'Open modal' button again to show the modal popup it shows the message then saying it was submitted, meaning I cant post again without reloading the page.
How would I be able to make it show the message without closing the modal, and also when I close, then open it back up [without reloading] it'll return back to my form instead of having a message.
Thanks.
My code: [Might not be exact as I cut a few un-needed things out]
<?php
echo '
<div style="float:left;margin-top:-51px;margin-left:141px;"> <!-- Button trigger modal -->
<button class="btn btn-primary btn-sml" data-toggle="modal" data-target="#myModal">
Send private message
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Send a message to '.$row["username"].'</h4>
</div>
<div class="modal-body"> ';
if($_POST[add2]){
$subject = strip_tags($_POST['title']);
$content = $_POST['content'];
$date = date("F jS, Y g:i a");
$receiver = $row["id"];
$sender = $member["id"];
if(!$content){
echo 'All fields are required';
}else{
$sql = $dbh->prepare("INSERT INTO `inbox` (`receiver`, `sender`, `subject`, `content`, `date`, `status`) VALUES ('$receiver', '$sender', '$subject', '$content', '$date', 'unread')");
$sql->execute();
$q = $sql->fetch(PDO::FETCH_ASSOC);
if($sql){
echo '<center>Message sent!</center>';
}else{
echo '<strong>Error:</strong> '.mysql_error();
}
}
}else{
echo '
<div style="overflow:auto;"><form method="post">
<div style="float:left;width:550px;">Subject<br>
<input type="text" name="title" id="title" class="form-control" value="" size="50" maxlength="40">
<br>Message<br>
<textarea style="height:85px;max-width: 550px;" class="form-control" name="content" placeholder="Enter your message here..." ></textarea></div>
<br><hr></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" style="margin-left:10px;" class="btn btn-primary" name="add2" value="Post">
</form>
</div> '; }
?>