I want to accept user data from a form, use AJAX to post the values to a PHP script, which will insert them into the database.
JQuery:
$(".add").click(function(){
var order = {
Name: $name.val(),
Drink: $drink.val(),
}
$.ajax({
type: 'POST',
url: '/ajax/api/orders.php',
data: order,
success: function(newOrder){
$orders.append('<li>Name: ' + newOrder.Name +', Drink: '+ newOrder.Drink +'</li>')
}
})
});
Php:
//open connection to mysql db
$connection = mysqli_connect("localhost","root","xxxxxxxxx","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from orders";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$name = $_POST["Name"];
$drink = $_POST["Drink"];
$sql2 = "INSERT INTO orders (Id, Name, Drink) VALUES (NULL, '$name', '$drink')";
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
can somebody help me with it?
i think you should insert before you get all orders
$name = $_POST["Name"];
$drink = $_POST["Drink"];
$sql2 = "INSERT INTO orders (Id, Name, Drink) VALUES (NULL, '$name', '$drink')";
mysqli_query($connection, $sql) or
die("Error in Inserting" . mysqli_error($connection))
$id = mysqli_insert_id ($connection);
$sql = "select * from orders where Id = $id";
$result = mysqli_query($connection, $sql) or
die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
The javascript will be right this:
$(".add").click(function(){
var order = {
Name: $name.val(),
Drink: $drink.val(),
}
$.ajax({
type: 'POST',
url: '/ajax/api/orders.php',
data: order,
success: function(newOrder) {
$.each(newOrder, function(order) {
//$order is a ul that have id = orders
$orders.append('<li>Name: ' + order.Name +', Drink: '+ order.Drink +'</li>');
});
}
});
});
and if you need anything ask :]
UPDATE
please update the success function you have to this
success: function(data) {
data.forEach(function(order) {
//$orders is a ul that have id = orders
$orders.append('<li>Name: ' + order.Name +', Drink: '+ order.Drink +'</li>');
});
}
UPDATE 2
success: function(data) {
var obj = JSON.parse(data);
var length = obj.length;
for (var i = 0; i < length; i++) {
$orders.append('<li>Name: ' + obj[i].Name +', Drink: '+ obj[i].Drink +'</li>');
}
}
UPDATE 3
$name = $_POST["Name"];
$drink = $_POST["Drink"];
$sql2 = "INSERT INTO orders (Id, Name, Drink) VALUES (NULL, '$name', '$drink')";
mysqli_query($connection, $sql2) or
die("Error in Inserting" . mysqli_error($connection))
$id = mysqli_insert_id($connection);
$sql = "select * from orders where Id = $id";
$result = mysqli_query($connection, $sql) or
die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
Related
I have a PHP and Javascript code that I am using for my typeahead search feature and it is working fine. But if you look at the code below, I am passing the search value, how can I grab the id and pass to the form URL?
HTML
<form method="get" class="form-inline customers" autocomplete="off" action="/customers/<?php echo id; ?> ">
<input class="customers" id="customers" type="text" name="customers">
<button type="submit" title="Search Customers"></button>
</form>
Javascript
<script>
$( document ).ready(function() {
$('input.customers').typeahead({
source: function (query, process) {
var countrycode = '<?php echo $agencyid; ?>';
return $.get('fetch_customers.php', { query: query, cc: countrycode }, function (data) {
data = $.parseJSON(data);
return process(data);
});
},
});
});
</script>
PHP
$countrycode1 = $_GET['cc'];
$sql="SELECT
first_name,
last_name,
id,
status,
agency_id
FROM customers
WHERE (agency_id = '$countrycode1') AND first_name LIKE '%".$_GET['query']."%' LIMIT 20";
$resultset = mysqli_query($conn, $sql) or die("database error:".
mysqli_error($conn));
$json = array();
while( $rowscity = mysqli_fetch_assoc($resultset) ) {
$json[] = $rowscity["first_name"];
$json[] = $rowscity["id"];
}
$output = json_encode($json);
echo $output;
mysqli_close($conn);
?>
Your PHP Script:
<?php
$countrycode1 = $_GET['cc'];
$sql = "SELECT
first_name,
last_name,
id,
status,
agency_id
FROM customers
WHERE (agency_id = '" . $countrycode1 . "') AND first_name LIKE '%" . $_GET['query'] . "%' LIMIT 1";
$resultset = mysqli_query($conn, $sql) or die("database error:" . mysqli_error($conn));
$json = array();
while ($rowscity = mysqli_fetch_assoc($resultset)) {
echo $rowscity["id"]; exit;
}
?>
Your Script can be like:
<script>
$(document).ready(function () {
$('input.customers').typeahead({
source: function (query, process) {
var countrycode = '<?php echo $agencyid; ?>';
$.get('fetch_customers.php', {query: query, cc: countrycode}, function (data) {
$('form').attr('action', '/customers/' + data);
});
},
});
});
</script>
how do I concat two columns? I need it to have FIRSTNAME AND LASTNAME to equal $Employee_Name I tried different combinations and still doesn't work. Also I know this has a huge SQL injection issue. I do not know yet how to correct the issue I am looking it up.
<?php
header('Content-Type: application/json');$db_conx = mysqli_connect("localhost", "root", "systems399","employees_db");
$Employee_Name= $_POST["Employee_Name"];
$sql="SELECT * FROM names WHERE FIRSTNAME='$Employee_Name' ";
$query= mysqli_query($db_conx, $sql);
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$rc= $row["EMPLOYEE_NUMBER"];
echo json_encode ($rc);
?>
I tried it this way and it doesn't work.
<?php
header('Content-Type: application/json');
$db_conx = mysqli_connect("localhost", "root", "systems399", "employees_db");
$Employee_Name= $_POST["Employee_Name"];
$sql="SELECT * FROM names WHERE FIRSTNAME='$Employee_Name' AND LASTNAME='$Employee_Name'";
$query= mysqli_query($db_conx, $sql);
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$rc= $row["EMPLOYEE_NUMBER"];
echo json_encode ($rc);
?>
Here is my Javascript code
$(document).ready(function() {
$("#Employee_Name").change(function() {
var Employee_Name = $(this).val();
if (Employee_Name != '') {
$.ajax({
type: "post",
url: "insert.php",
data: "Employee_Name=" + Employee_Name,
datatype: "json",
success: function(data) {
$("#Employee_Number").val(data);
$('#Employee_Number').css("background-color", "#B3CBD6")
$('#Employee_Number').animate({
backgroundColor: "#ffffff"
});
},
error: function(response) {
alert("error scripting")
}
});
} else {
$("#Employee_Number").val("");
}
});
});
There are 2 posibilities:
1.
$sql = "SELECT CONCAT(`FIRSTNAME`, ' ', `LASTNAME`) AS `EmployeeName`, * FROM `names` HAVING `EmployeeName` = '".$Employee_name."'";
2.
$sql = "SELECT * FROM `names` WHERE CONCAT(`FIRSTNAME`, ' ', `LASTNAME`) = '".$Employee_name."'";
Here is an example -
$sql = "SELECT CONCAT(`FIRSTNAME`, ' ', `LASTNAME`) AS `EmployeeName`, * FROM `names` WHERE `FIRSTNAME` = '" . $First_Name . "' AND `LASTNAME` = '" . $Last_Name' . "' ";
I have two tables one for user and one for search. When I drag a search over to user it adds entire search list. How do I only insert the item dragged and not the entire search array?
THE PROBLEM IS recordsArray.
<?php
require("db.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray = $_POST['recordsArray'];
if ($action == "updateRecordsListings"){
$listingCounter = 1;
foreach ($updateRecordsArray as $recordIDValue) {
$query = "UPDATE records1 SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, update query failed');
//INSERTS array item that does NOT EXIT in userTable
if (mysql_affected_rows()==0) {
$query = mysql_query("INSERT INTO records1 SELECT * FROM records WHERE recordID = " . $recordIDValue);
$query = "UPDATE records1 SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, insert/update query failed');
}
$listingCounter = $listingCounter + 1;
}
echo '<pre>';
print_r($updateRecordsArray);
echo '</pre>';
echo 'If you refresh the page, you will see that records will stay just as you modified.';
}
?>
Both list arrays id must maintain the same id names in order for the above item to acknowledge and process the list items. Keeping things simple I just used the same code for the Search, User format:
<li id="recordsArray_<?php echo $result['recordID']; ?>"><?php echo $result['recordID'] . ". " . $result['recordText']; ?></li>
Javascript:
$(function() {
$("#contentLeft ul, #main ul").sortable({ accept: '.draggable', connectWith: "#contentLeft ul", opacity: 0.6, cursor: 'move', update: function() {
var order = $(this).sortable("serialize") + '&action=updateRecordsListings';
$.post("updateDB.php", order, function(theResponse){
$("#contentRight").html(theResponse);
});
}
});
}).disableSelection();
});
How can I call only the recordsArray items from #content ul?
I can only get one insert per refresh with this but it does drag and drop insert...
Still need an if statement for possible errors because +/-1 if
<?php
require("db.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray = $_POST['recordsArray'];
$uRA = $updateRecordsArray;
// Get total number of elements in $updateRecordsArray
$ifArray = $updateRecordsArray;
$resultCount = count($ifArray);
//echo '<br />';
//print_r($resultCount);
// Get total number of rows in $records1
$recordTable = array();
$result = mysql_query("SELECT recordListingID FROM records1");
$numRows = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
$recordTable = array_merge($recordTable, array_map('trim', explode(",", $row['recordListingID'])));
}
//Gets $id/$val of elements not in both arrays
$results = array_diff($uRA, $recordTable);
//echo '<br />';
//print_r($numRows);
//Give variables for +/- 1 $numRows
$plusNumRows = $numRows + 1;
$minusNumRows = $numRows - 1;
//echo '<br />';
//print_r($minusNumRows);
// Normal jQuery drag and drop ranking found online
if ($action == "updateRecordsListings"){
$listingCounter = 1;
foreach ($updateRecordsArray as $recordIDValue) {
//If statement for for +/- 1 $numRows
If ($resultCount == $numRows -1 || $resultCount == $numRows || $resultCount == $numRows + 1){
$sql = mysql_query("INSERT INTO records1 SELECT * FROM records WHERE recordID = $recordIDValue");
}
$query = "UPDATE records1 SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, update query failed');
$listingCounter = $listingCounter + 1;
}
echo '<pre>';
print_r($updateRecordsArray);
echo '</pre>';
echo 'If you refresh the page, you will see that records will stay just as you modified.';
}
?>
id car make sales
1 panamera porsche 100
2 italia ferrari 200
3 volante astonmartin 300
4 avantador lamborghini 400
5 slk mercedes 500
So guys, i have this simple table in my database. And i'm gonna echo this table in a while loop.
<ul>
<?php
$query = "SELECT * FROM inplace LIMIT 0, 6";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
while ($row = mysql_fetch_assoc($result)) {
echo '<li class="editable" data-id="'.$row['id'].'" data-col="car">'.$row['car'].'</li>';
echo '<li class="editable" data-id="'.$row['id'].'" data-col="make">'.$row['make'].'</li>';
echo '<li class="editable" data-id="'.$row['id'].'" data-col="sales">'.$row['sales'].'</li>';
}
?>
</ul>
The idea is to update this table using jQuery in-place editor. So here is the code-
$(document).ready(function()
{
$(".editable").bind("dblclick", replaceHTML);
$(".editable2").bind("dblclick", replaceHTML2);
$(".btnSave, .btnDiscard").live("click", handler);
function handler()
{
if ($(this).hasClass("btnSave"))
{
var str = $(this).siblings("form").serialize();
$.ajax({
type: "POST",
async: false,
url: "handler.php",
data: str,
});
}
}
function replaceHTML()
{
var rowId = $(this).parent('li').data('id');
var colName = $(this).parent('li').data('col');
var buff = $(this).html()
.replace(/"/g, """);
$(this).addClass("noPad")
.html("<form><input type=\"text\" name=\"" + colName + "\" value=\"" + buff + "\" /> <input type=\"text\" name=\"buffer\" value=\"" + buff + "\" /><input type=\"text\" name=\"id\" value=\"" + rowId + "\" /></form>Save changes Discard changes")
.unbind('dblclick', replaceHTML);
}
}
);
This is an in-place edit code i got it from the internet and i just tore it down to basic level just to understand the codes. Behrang Saeedzadeh helped me improvise "replace HTML" function.
And here is the update query in handler.php file -
<?php
require("db.php");
if (isset($_POST['id']) && isset($_POST['car'])) {
$id = mysql_real_escape_string($_POST['id']);
$car = mysql_real_escape_string($_POST['car']);
$query = "UPDATE inplace SET car ='$car' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
else if (isset($_POST['id']) && isset($_POST['make'])) {
$id = mysql_real_escape_string($_POST['id']);
$make = mysql_real_escape_string($_POST['make']);
$query = "UPDATE inplace SET make ='$make' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
else if (isset($_POST['id']) && isset($_POST['sales'])) {
$id = mysql_real_escape_string($_POST['id']);
$sales = mysql_real_escape_string($_POST['sales']);
$query = "UPDATE inplace SET sales ='$sales' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
?>
Here in the update query, i have to write a different query for each column. The question is how do i update using only one query for all the columns?
if(isset($_POST['id']) {
$id = mysql_real_escape_string($_POST['id']);
$arr_check = array("car", "make", "sales");
$result = array();
foreach($arr_check as $check) {
if(isset($_POST[$check]))
$result[] = $check . '="' . mysql_real_escape_string($_POST[$check]) . '"';
}
$result = implode(", ", result);
if($result != '') {
$query = "UPDATE inplace SET {$result} WHERE id='{$id}'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) echo 1;
}
}
that should more or less do it
First of all, you might be better off making the entire list a form to begin with, and storing the existing records in hidden form fields. Then, you should have the handler.php script check if any new form entries were submitted, and store them into variables. If no new entry was made, the variables will contain the default value.
Then, you can submit the whole update query in one shot:
$query = "UPDATE inplace SET car ='$car', make='$make', sales='$sales' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) echo 1;
if(isset($_REQUEST['SAVE'])) {
$sql = "SELECT SecName FROM section WHERE SecID='$section'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)){
$SecName = $row["SecName"];
}
$sql = "SELECT SubjName FROM subject WHERE SubjID='$subject'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)){
$SubjName = $row["SubjName"];
}
$check = mysql_query("SELECT SecID FROM service where SubjID='$SubjName'")or die(mysql_error());
$bool = 1;
while($info = mysql_fetch_array( $check ))
if(($info['SecID'] == $SecName)){
$bool = 0;
}
if($bool){
$check = mysql_query("SELECT * FROM service ")or die(mysql_error());
$bool = 1;
while($info = mysql_fetch_array( $check ))
if(($info['Start_date'] == $Start_date) && ($info['Venue'] == $Venue) || ($info['Start_date'] == $Start_date) && ($info['Facilitator'] == $Facilitator)){
$bool = 0;
}
if($bool){
$sql="INSERT INTO service ( ServiceID, Date, Semester, School_year, Start_date, Venue, Facilitator, Stype, SecID, SubjID)VALUES('$RecCode','$Date','$Semester','$School_year','$Start_date','$Venue','$Facilitator','$Stype', '$SecName', '$SubjName')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo '<script type="text/javascript">';
echo 'alert("Save Successfully!");';
echo 'window.location="Admin_RecSchedMapLst.php";';
echo '</script>';
mysql_close($con);
}else
{
echo '<script type="text/javascript">';
echo 'alert("Conflicting schedule for Venue or Facilitator!");';
echo '</script>';
}
}else
{
echo '<script type="text/javascript">';
echo 'alert("The SECTION has been already scheduled!");';
echo '</script>';
}
}
/* $result = mysql_query("SELECT SIDno FROM class WHERE SecID=$SecID AND SubjID=$SubjID");
$row = mysql_fetch_assoc($result);
$SIDno = $row['SIDno'];
$result = mysql_query("SELECT ServiceID FROM service WHERE SecID=$SecID AND SubjID=$SubjID");
$row = mysql_fetch_assoc($result);
$ServiceID = $row['ServiceID'];
$sql="INSERT INTO registered ( ServiceID, IDno, Stype )VALUES('$ServiceID','$SIDno','$Stype')"; */
}
this code is working correctly,. i just want to ask how can i possibly work on the code whcih is commented above. all i want to do is when the serviceid is inserted i want also to immediately insert the serviceID, idno, type to another table which is registered.
It's much easier and better to use the mysql_insert_id function to get the ID of the row you just inserted, rather than doing another SELECT. E.g.:
$sql="INSERT INTO service ( ServiceID, Date, Semester, School_year, Start_date, Venue, Facilitator, Stype, SecID, SubjID) VALUES ('$RecCode','$Date','$Semester','$School_year','$Start_date','$Venue','$Facilitator','$Stype', '$SecName', '$SubjName')";
if (mysql_query($sql,$con)) {
$ServiceID = mysql_insert_id();
$sql="INSERT INTO registered ( ServiceID, IDno, Stype )VALUES('$ServiceID','$SIDno','$Stype')";
mysl_query($sql, $con); // check for error here too though
}
else {
echo "OH NO!!!";
}
Also, beware of SQL injection with the way you're building your SQL strings.
Execute another SQL INSERT command after the first one, like:
$sql="INSERT INTO service ( ServiceID, Date, Semester, School_year, Start_date, Venue, Facilitator, Stype, SecID, SubjID) VALUES ('$RecCode','$Date','$Semester','$School_year','$Start_date','$Venue','$Facilitator','$Stype', '$SecName', '$SubjName')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
/*Begin your SELECT and INSERT code*/
$result = mysql_query("SELECT SIDno FROM class WHERE SecID=$SecID AND SubjID=$SubjID");
$row = mysql_fetch_assoc($result);
$SIDno = $row['SIDno'];
$result = mysql_query("SELECT ServiceID FROM service WHERE SecID=$SecID AND SubjID=$SubjID");
$row = mysql_fetch_assoc($result);
$ServiceID = $row['ServiceID'];
$sql2 = "INSERT INTO registered ( ServiceID, IDno, Stype )VALUES('$ServiceID','$SIDno','$Stype')";
/*End your SELECT and INSERT code*/
if(!mysql_query($sql2,$con))
{
die('Error: ' . mysql_error());
}
}