PHP show message box for update query status - php

I'm new in PHP, so I'm not sure how to show message box or dialog box containing message to show update query status (the update query is set to work on MYSQL).
--Here is my Code--
session_start();
include_once("../classes/cls_main.php");
$connection = new MainClass();
$connection->createConnection();
$connection->selectDatabase();
$strSQL = "Update tr_routing set Worktatus = 'Sync' ,Sync_Date = Now() WHERE WorkStatus = 'Done' and UserID IN (SELECT UserID FROM ms_user WHERE UserName = '" . $_GET['kode'] . "') ";
$rs = $connection->CRUD_Data($strSQL);
if(mysql_query($strSQL)){
echo "Success update";
}else{
echo "No rows update";
}
$connection->closeConnection();
--End Of Code--
the PHP is trigger by jScript, the jScript is trigger by button on html file.
Thank You in Advance for answering

you may use jquery for this.
var result = $.get( "your_query_file.php", function(data) {
alert( data );
}).fail(function() {
alert( "error" );
});

Put the below code to display the message when rows are updated or if they are not
<?php
if(mysql_query($strSQL))
{
?>
<script>
alert('Rows are updated successfully');
</script>
<?php
}
else
{
?>
<script>
alert('No rows updated');
</script>
<?php
}
?>

Related

Deleting a row with AJAX+php failing

The code should work the following way: Press a button -> row gets deleted from database.
I tried to follow and copy answers from other questions but with no working solution.
The jquery code:
$(document).on('click', ".menuRemove", function(event) {
var del_h3name2 = $(this).parent().parent().prev().text();
$.ajax({
type:'POST',
url:'deleteaccordion2.php',
data:{'del_h3name2':del_h3name2},
success: function(data){
if (data=="YES") {
alert("YES")
} else {
alert("can't delete the row")
}
}
});
}
and php code (deleteaccordion2.php):
<?php
require 'database.php';
if ( isset($_SESSION['user_id']) ) {
$id = $_SESSION['user_id'];
$accordion = $_POST['del_h3name2'];
echo '$accordion';
$delete = "DELETE FROM useraccordion WHERE id='$id', h3= '$accordion' ";
$result = mysqli_query($delete);
if ($result) {
echo "YES";
} else {
echo "NO";
}
}
?>
You didn't add the html so I really don't know if the value you are sending is correct, but you do have error in your SQL syntax:
DELETE FROM useraccordion WHERE id='$id', h3= '$accordion'
^ This is wrong.
You can DELETE where id = x AND h3 = y:
$delete = "DELETE FROM useraccordion WHERE id='$id' AND h3= '$accordion' ";
Note that your code is vulnerable for SQL injections (read about boby tables).

Update Text Value in PHP form display using jQuery & MySQL database

I have a table display and I want to enable users to edit the values of the table in a live way using jQuery. The table is simple, it just has 1 column with a list of names. I have it all built out but at the moment the table doesn't update the value. All the code is below, I am still learning everything so it's probably not written very well/correctly! Thanks in advance.
Form Display:
<?php
echo "<div class=\"table-responsive\"><table class=\"table table-striped\">";
echo "<thead><tr><th>Employee Name</th><th></th></tr></thead><tbody>";
require_once 'connectionsettings.php'; // Gets connection settings
$sql = "SELECT id, employees FROM Employees ORDER BY employees ASC";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// what it's saying is that if there's rows do something
while($row = $result->fetch_assoc()) {
// now it's saying get the data and put it in rows
echo "<tr><td data-id='{$row['id']}' contenteditable=\"true\">" . $row["employees"] . "</td><td><span data-id='{$row['id']}' name='remove_{$row['id']}' class='employee glyphicon glyphicon-remove' aria-hidden='true'></span></td></tr>";
}
}else{
echo "No Employees! Let's add some.";
}
$mysqli->close();
echo "</tbody></table></div>";
?>
Jquery Info:
$(function(s){
$("td[contenteditable=true]").blur(function(){
var id = $(this).attr("id") ;
var name = $(this).text() ;
var formURL = "updateemployeename.php";
$.ajax({
url : formURL,
type: "POST",
data : {name: name, id: id},
success:function(data, textStatus, jqXHR)
{
$('#successmessage2').slideDown('fast').delay(1500).slideUp('fast');
$('div#employeedisplay').hide();
$('div#updatedemployeedisplay').load('employeedisplay.php').fadeIn(3000);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
});
s.preventDefault(); //STOP default action
});
SQL Info:
<?php
require_once 'connectionsettings.php'; // Gets connection settings
$name = htmlspecialchars(trim($_POST['name']));
$id = htmlspecialchars(trim($_POST['id']));
$sql = "UPDATE Employees SET employees='$name' WHERE id='$id'";
if($mysqli->query($sql) === TRUE) {
echo "status updated successfully";
}else{
echo "Error updating status" . $mysqli->error;
}
$mysqli->close();
?>

How to get database retrieved value in jquery?

I want to update a likes on database when a user clicks on "like"(same as facebook like). I will load various posts from database. For each posts there is a unique field on database called mid(message Id) and when user clicks "like" below the post i want to increment likes on database for that specific message(it can be through mid). I want to implement this function using jquery because if i pass mid through url it will navigate to that page and get loaded whole page so i need to done it behind the page through AJAX call. Let me show a model how my database retrieval is
$cot = "select * from posts where userid = $usr LIMIT 10";
$ex = mysql_query($cot, $con);
while($cont = mysql_fetch_array($ex))
{
$date = date_create($cont['date']);
$mid = $cont['mid'];
echo "<div id='posts'>";
echo $cont['message'];
echo $photo;
echo "<div class='like'>"; //echo $mid; /* It is to show message id*/
echo "<a href='#'>Like</a></div>"; //When Clicked Like i Want to increment likes on DB
echo "Likes(" . $cont['Likes'] . ")";
echo date_format($date, 'd-m-Y H:i:s');
echo "<hr>";
echo "</div>";
}
i want this to be done over jquery and ajax call. I just need jquery code to call php file increment.php and pass mid(message Id) to that page.
maybe you need something like this:
echo "<a href='javascript:void(0);' class='like' data-mid='".$cont['mid']."'>Like</a></div>"; //When Clicked Like i Want to increment likes on DB
Now this is the script:
<script type="text/javascript">
$(function(){
$(".like").live('click', function(){
$.ajax({
url : 'increment.php',
data : {'mid':$(this).data('mid')},
type : 'POST',
success : function(resp){
if(resp == '1'){
//success message or whatever
}
},
error : function(resp){
alert("some error occured !");
}
});
});
});
</script>
On your increment.php:
<?php
$id = $_POST['mid'];
$sql = "update posts set Likes = Likes+1 where mid = '".$id."'";
//execute the above and return some thing
return 1;
?>
$.post('/increment.php', { mid: whatever });
With your example click handler, it's simple to add this in....
$(document).ready(function() {
$("div.pray").click(function() {
var mid=$(this).val();
alert(mid);
$.post('/increment.php', { mid: mid });
});
});

my post doesn't insert in my database

I am creating a facebook like posting system..
My problem today is it doesn't seem to insert the value i get from the text area into my data base..
here is my java script:
$("#share").click(function()
{
//var typeNew = document.getElementById("content").value;
var update = $( "textarea#content" ).val();
//document.write(update);
if(update.length == 0)
{
alert("empty, please type something.");
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
}
else
{
//$("#flash").show();
$("#flash").html('<img src="loader.gif" />Loading Comment...').fadeIn("slow");
$.ajax({
type: "POST",
url: "post_update.php",
data: 'update=' + update,
success: function(msg)
{
$("#flash").ajaxComplete(function(event, request, settings){
//alert("Successfully Inserted")
$("#flash").hide();
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
});
}
});
}
return false;
});
then here is my php code:
<?php
$post=$_REQUEST['update'];
$post=$_POST['update'];
//echo '$post';
# $db = new mysqli('localhost', 'root', '', 'wall');
if(mysqli_connect_errno())
{
echo "Error! Could not connect to database. Reset fields.";
exit;
}
$sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
$result = $db->query($sql);
if($result){
echo 'OK';
}
else{
echo 'FAIL';
}
$db->close();
?>
can someone tell me what's wrong?
it worked well when the delete function was in error but now that it's functional my share function does not work..
In your PHP code you have the following lines:
$post=$_REQUEST['update'];
$post=$_POST['update'];
You shouldn't have these both. In Your case, You actually need only the second one but for testing, try commenting it out leaving only the $_REQUEST line. Now you can pass parameters by GET too.
To see, if the query is correct, print it out too like this:
echo $sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
Now direct your browser to that location your.domain/post_update.php?update=testmessage and see the output.
If everything seems to be working, replace the POST/REQUEST lines with this:
$post=$db->real_escape_string($_POST["update"]);
I ran into this the other day. Use autocommit or start and commit transactions. Also, try a semicolon at the end of your statement (probably not the issue).
http://dev.mysql.com/doc/refman/5.0/en/commit.html
If your $post is coming out to be fine then try:
$post = $db->real_escape_string($_POST["update"]);
if (!db->query("INSERT INTO posts(update,date_posted) VALUES('$post' ,NOW())")) {
echo $db->sqlstate; //show error
}
else {
echo "inserted";
}
Assuming the column type of update is varchar / charand date_posted is datetime:
$sql = sprintf("INSERT INTO posts(update,date_posted) VALUES('%s',NOW())",
mysql_real_escape_string($post));
$result = $db->query($sql);
Please change the column name "update" to anyother. it may works. And Avoid some predefined varibales for column names.
Hope it helps.

Table doesn't respond to second jQuery request

My PHP script generates a table with rows which can optionally be edited or deleted. There is also a possibility to create a new Row. The PHP is activated through jQuery Events.
Now all works well, I can edit delete and create an Item. After each action which makes use of the PHP script the HTML table gets updated.
But when I try after an Event to do an action again the HTML Table doesn't get updated though in the background the PHP script makes an entry into the database.
Does someone of you know why my HTML Table doesn't update itself when I trigger a second event?
Here is the Script:
PHP
<?php
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD)
or die ("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME,$dbh)
or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if($action == "new")
{
mysql_query("INSERT INTO `place` (`id`, `name`) VALUES (NULL, '$name')");
}
elseif($action == "edit")
{
mysql_query("UPDATE `place` SET `name` = '$name' WHERE `id` = '$id'");
}
elseif($action == "delete")
{
mysql_query("DELETE FROM place WHERE id = '$id'");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=".$row["id"]." class=inputfield_td><input class=inputfield_place type=text value=".$row["name"]." /></td><td class=place_name>".$row["name"]."</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
?>
JS
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function (html){
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display","none").prevAll(".place_name").css("display","none").prevAll(".inputfield_td").css("display","block").nextAll(".cancel").css("display","block").nextAll(".save").css("display","block").prevAll(".inputfield_td").css("display","block");
});
$(".cancel").live("click", function() {
myvariable5 = $(this).prevAll(".place_name").html();
$(this).css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none").nextAll(".save").css("display","none").siblings().find("input[type=text]").val(myvariable5);
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display","none").prevAll(".cancel").css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none");
$.post("place/place_list.php", {action: "edit", name: ""+myvariable1+"", id: ""+myvariable2+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
$.post("place/place_list.php", {action: "delete", id: ""+myvariable3+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {action: "new", name: ""+myvariable4+""}, function (html){$("#place_container").replaceWith(html);});
});
});
I think I know. You do replaceWith instead of append, so your DIV with ID #place_container disappears after the first operation (you are left with only a table in your page), and of course jQuery does not find it and is unable to refresh it with new content from the second operation.
Just use append or, better yet, html methods.
Shouldnt you replace the complete table ?
$("#place_container").html(html);

Categories