I have a function in JavaScript with the following parameters below:
insertdata(micheal, newyork)
I want to be able to insert thus:
name = micheal
location = newyork
into my MySQL database using PHP and jQuery.
Both items of data are not coming from a form. I'm only passing them from JavaScript.
Since I cannot comment due to reputation, I suggest you a solution that through jQuery you can append this to your current form as hidden fields and these get submitted at the PHP backend and you can save it in your DB.
Let me know if you need help on how to append it to the form.
var name = $("<input type='hidden' name='whatever' value='micheal' />");
$("#myform").append(name);
Also have a look at this
Add elements using jQuery dynamically
To process this in PHP see this,
$variable_name_1 = $_POST['name_of_form_field_1'];
$variable_name_2 = $_POST['name_of_form_field_2'];
//Read how to sanitize variables
$query = "INSERT INTO table_name (field1, field2) VALUES ('$variable_name_1', '$variable_name_2')";
$result = mysqli_query($query);
if(!$result) {
echo "Error" . mysqli_error();
}
else {
echo "Done!";
}
You can have a snapshot of your form submitted by doing this var_dump($_POST)
Related
I have data which is a name. And I am having an input type=text where the value is equals to the name, together with a button type=submit. So what i'm trying to do is that, i want to change and update the name in my database and also output the new name without reloading the page at once because I want to run a JS function (Not Alert but a Toast Notification) which is I cannot do. So to shorten, ( EDIT -> UPDATE -> SHOW = without reloading the page).
EDIT:: I'm sorry I forgot to mention. I know jQuery and AJAX is the solution but I am having trouble understanding AJAX not unlike jQuery.
profile.php (FORM CODE)
<form action="profile.php" method="POST">
<input type="text" id="changename" name="changename" class="form-control" placeholder="New Name" required>
<button id="btnchange" type="submit"></button>
</form>
profile.php (PHP CODE)
<?php
if(isset($_POST['changename'])) {
require 'connect.php';
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
$sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'";
if(mysqli_query($conn, $sql)){
header('location: profile.php');
// MY JS FUNCTION HERE //
}
mysqli_close($conn);
}
?>
How to update and output a databse without reloading the page? what u looking for is AJAX.
I know you have selected the answer, but there's an extra information that you need that might help you in the long run
The are some good ajax tutorials you can follow in the web
Ajax Introduction
What is Ajax ?
And many more you can find on the web.
This is what u need to do, first your form method is GET and on your php script you are requesting an $_POST therefore this will generate an undifined notice error,changename : notice : undifined variable changename so the solution is to use one method in a single form if your form is $_GET you use $variable = $_GET['fieldname'] if form method is POST on your server side use $variable = $_POST['fieldname']; not the way you did. So lets change your form method to POST Then this is what u should do.
edit.php
Update
<script type="text/javascript">
$('document').ready(function(){
$('form').on('submit',function(event){
event.preventDefault();//prevent the form from reloading the page when submit
var formData = $('form').serialize(); // reading form input
$.ajax({
type :'POST',
data : formData,
url : 'profile.php',
dataType : 'json',
encode : true,
success : function(response){
//response = JSON.parse(response);
if(response == "ok"){
$('#success').html('profile updated success');
setTimeout(' window.location.href = "profile.php"; ', 6000); // redirecting
}else{
//could not update
$('#error').html(response);
}
},
error : function(e){
console.log(e); // debugging puporse only
}
});
});
});
</script>
That's what you need on the frontend side.. Please note if you have more than one form in a single page then do not use $('form').on('submit',function(event){}); you then give each form a unique ID then on replace the form on jquery/ajax with the iD of the form u wanna submit.
Then your server side.
I have noticed that you have header('location: profile.php'); that's
for redirecting, since we are sending ajax request to the server and
back to the client, you don't redirect on the server side, your
redirect using the client side after you have received the response
you expected from the server. I have commented that section where I do
redirecting with client side, on the script above.
profile.php
<?php
$message = '';
if(isset($_POST['submit'])) {
require 'connect.php';
//validate your input field
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
$sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'";
if(mysqli_query($conn, $sql)){
$message = 'ok'; // success
}else{
$message = 'system error could not update please try again later';
}
echo json_encode($message);//sending response back to the client
mysqli_close($conn);
}
?>
That's all you need, note you need to validate all your inputs fields in both the client and server side before using them.
I would also advice you to learn more about prepared statements, using mysqli or PDO they are very easy to use and very safe.
running a query like this : $sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'"; is very unsafe, your inputs are not validated and not filtered and sanitized.
so with prepared statements its easy like :
profile.php prepared
<?php
$message = '';
if(isset($_POST['submit'])) {
require 'connect.php';
//validate your input field
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
//prepare and bind
$sql = $conn->prepare("UPDATE login SET login_name= ? WHERE user_id= ? ");
$sql->bind_param("si",$newname,$user_id);
if($sql->execute()){
$message = 'ok';
}else{
$message = 'Error Could not update please try again later';
}
echo json_encode($message);
$conn->close();
}
?>
$sql->bind_param("si",$newname,$user_id); This function binds the parameters to the SQL query and tells the database what the parameters.
are.By telling mysql what type of data to expect, we minimize the risk of SQL injections.
First thing to do in your form is to change your form method to POST (and not GET) as you try to retrieve "changename" by POST method.
So change this:
<form action="profile.php" method="GET">
by this:
<form action="profile.php" method="POST">
I've put certain values like a user id into the url e.g /index.php?id=1 in previous PHP files.
I have a HTML form that has an action like this:
<form name="staffResponse" method="post" action="respond_ticket.php?id=<?php echo $_GET['id']; ?>">
Which when you go to respond_ticket.php and simply echo the value for the id and look at the URL it does it successfully. Whats more the data that I am posting to that file is also done without problem. However I want to then write that information to a table but it does not seem to work.
Here is the respond_ticket.php file
<?php
include 'database/db.php';
$id = $_GET['id'];
$staffResponse = $_POST['staffResponse'];
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse') WHERE id='$id'";
$result = mysqli_query($connection, $sql);
if ($result === TRUE) {
echo '<p>Response ' . $staffResponse . ', has been added</p>';
}
else {
echo '<p class="warning">Unable to respond</p>';
}
?>
The db.php file has all the necessary information for connection to the database i.e name password etc. It also opens the question there too.
I keep just getting the warning message that I wrote.
you cant do an insert with a where modifier like this. change it to update ;)
UPDATE tickets SET staffResponse = '$staffResponse' WHERE id = '$id'
You are not supposed to use a WHERE clause with INSERT
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse')";
You may wish to set your tickets table up with auto increment so you dont need to insert an id if you haven't done that already.
use ON DUPLICATE UPDATE if it helps
INSERT INTO tickets (id,staffResponse) VALUES ('$id','$staffResponse')
ON DUPLICATE KEY UPDATE id=VALUES(id), staffResponse=VALUES(staffResponse)
I am using the following script to process a form that updates a message on my website, the problem I am having is that it is clearing the row instead of updating it for some reason. I have copied the query from Phpmyadmin so I know its correct, and I have also tried echoing the posted values and they all echo out just fine too, but for some unknown reason when I click submit in the form it just wipes the contents of the record instead of updating it.
<?php
include("connectmysqli.php");
if (isset($_POST['OnOff'])) {$OnOff = $_POST['OnOff'];}else {$OnOff = '';}
if (isset($_POST['title'])) {$title = $_POST['title'];}else {$title = '';}
if (isset($_POST['message'])) {$message = $_POST['message'];}else {$message = '';}
$stmt = $db->prepare("UPDATE `itsnb_chronoforms_data_urgentform` SET `title` = '$title',`message` = '$message',`OnOff` = '$OnOff' WHERE `cf_id` =1;");
if (!$stmt) trigger_error($db->error);
$stmt->execute();
echo 'Message Updated !';
echo '<p>Back To Main Menu</p>';
?>
This is the table :
did you echo the generated query?
there are exactly to ways I see this can happen:
your form input names do not match the post keys you check in the three if statements
you're not sending the form with method="post"
also you should only execute the update query if all three post fields are set and valid. like title and message must not be blank/empty and that onOff variable should eighter contain "on" or "off". otherwise echo an errormessage so the user knows what's wrong with his input.
I'm currently learning PHP. I've code a simple bucketlist script with a admin panel, sessions etc just to see if I can do it.
The last page I am coding is the "edit.php" & "editone.php" I have a table which returns all data within the database "ID, Goal & Rating" my fourth column returns "EDIT" as a link which will link off to: editone.php?id=xx
editone.php currently is not a page. For the life of me I cannot figure out how I code the editone so I can grab the data and UPDATE mysql. I'm almost there just cannot piece together the puzzle.
Here's the core of my code for the edit page.
<?php
while ($query_row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>".$query_row['id']."</td><td>". $query_row['goals']."</td><td><span class='label label-inverse'>". $query_row['rating']."</span></td><td><a href='editone.php?id=".$query_row['id']."'>Edit</a></td>";
echo "<tr>";
}
?>
Any assistance would be really appreciated.
Send all the parameters through POST method to editone page. I mean in your edit page, you are getting all the variables from database. You can show them in a form having a submit button and of type "POST". So now when someone submits, it goes to editone.php page.
Get all the variables first through $_POST method. Then write a update query.
$sql = "UPDATE tablename SET goals = '$goal', rating='$rating' WHERE id = $id";
make sure to escape your post variables as said in the comment.
This is how should be your PDO Update statement.
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$goals = 'Some goals';
$rating = 'whatever rating';
$id = 3;
// query
$sql = "UPDATE tablename
SET goals=?, rating=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($goals,$rating,$id));
If I understood you correctly, what you want is a page that first displays a single row (so it can be edited) and then saves it once you're done. So you start out by writing the HTML form with no data in it.
Next, you read the ID from the query string:
<?php
$rowId = $_GET['id'];
and then query for the data:
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "SELECT goals, rating FROM tablename WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($rowId));
$row = $query->fetch();
Now, you can use the data to populate your form. This gets you about halfway there. :-)
You'll want the actual save to be in response to a POST request, not GET. There's a long and somewhat complicated explanation on why that is, but the simplified version is that you use POST whenever you're making changes for the user, and GET when you're just reading data -- there's a bunch of browser and proxy behavior and whatnot tied to these assumptions, so it's a good idea to start doing things the right way early on.
When you process the POST request -- you can do it on the same page -- you'll have the updated form values for grabs, and you can use them to update your database:
// This can be a hidden field on the form...
$rowId = $_POST['id'];
$goals = $_POST['goals'];
$rating = $_POST['rating'];
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "UPDATE tablename SET goals = ?, rating = ? WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($goals, $rating, $rowId));
After this, your database should be updated. To finish things off, you'll probably want to redirect back to the page to make sure the form can't be double-submitted accidentally.
I haven't covered quite everything here, a bit on purpose. It's more fun when there are some blanks to fill in. :-)
You probably want your second <tr> to be </tr>.
The most common solution is to use an html form. The input values of this form are a select with the id in query string. When a submit button is pressed to save this, make a update. But I want share with you a good and complete web 2.0 example.
I have question regarding search on webpage with textbox and dropdown box.
I have table with fields:
ID
First name
Last name
Company name
Occupation
Description
Now i need to make search form which will be populated from database (field Occupation) and textbox where I can put whatever I want, and then get results from database based on those on web page.
I am really sorry but i am totally begginer and only need some examples of such kind of code and much help :)
Thank you
You're going to want to use AJAX to call a php script from your page and then use the php script to query your database and to echo the results back to the page.
I'm going to use jQuery for this example because it saves a lot of lines, you should check it out if you haven't already.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
function searchOccupation () {
$.ajax({
url: "searchOccupation.php?search=" + $('#searchTxt').attr('value'),
success: function (data) {
alert(data);
}
});
}
</script>
</head>
<body>
<input type="text" id="searchTxt">
<input type="button" value="Search" id="searchBtn" onclick="searchOccupation()">
</body>
Then your php script (whose name should match that in the "url" field of the ajax call (in this case it should be named "searchOccupation.php") will look like this:
<?php
$searchTxt = $_GET['search'];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli('server', 'user', 'password', 'database');
$sql = "SELECT * FROM tableName WHERE occupation = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param('s', $searchTxt);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
echo $row['firstName']; //This sends data back to the page
}
?>
The echo part of the php script is what sends data back into the "success: function (data)" of the javascript, so echo whichever field you want on the page as above.
Edit: Slightly misunderstood what you meant, ajon's above is probably what you need.