Submitting multiple database updates via PHP & JQuery - javascript

I'm stuck with trying to process multiple mySQL updates at the same time. I have 4 select/optiion boxes that pull entries from a db table. I want to be able to update the db onChange using JQuery. I have managed to get this working with one select module but as soon as I add more it spins out. I know that the main bad code is in db_submit.php but really not sure how else to write it. I know there has to be a cleaner way to do this.
FORM PAGE- INPUT.PHP
<html>
<head>
<script src="../assets/scripts/jquery-2.0.3.min.js"></script>
<script>
function updateDb() {
$.post("db_submit.php", $("#console").serialize());
}
</script>
<?php
include 'db_connect.php';
?>
</head>
<body>
<form id="console">
<select id="frame1" name="frame1" onChange="updateDb()">
<option value="">Select Channel</option>
<?php
$result = mysqli_query($con,"SELECT * FROM feedContent");
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['url'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
<select id="frame2" name="frame2" onChange="updateDb()">
<option value="">Select Channel</option>
<?php
$result = mysqli_query($con,"SELECT * FROM feedContent");
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['url'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
<select id="frame3" name="frame3" onChange="updateDb()">
<option value="">Select Channel</option>
<?php
$result = mysqli_query($con,"SELECT * FROM feedContent");
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['url'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
<select id="frame4" name="frame4" onChange="updateDb()">
<option value="">Select Channel</option>
<?php
$result = mysqli_query($con,"SELECT * FROM feedContent");
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['url'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
</form>
</body>
<?php
mysqli_close($con);
?>
</html>
PROCESSING PAGE- DB_SUBMIT.PHP
<?php
include 'db_connect.php';
$frame1= mysqli_escape_String($con,$_POST['frame1']);
$frame2= mysqli_escape_String($con,$_POST['frame2']);
$frame3= mysqli_escape_String($con,$_POST['frame3']);
$frame4= mysqli_escape_String($con,$_POST['frame4']);
$query = "UPDATE frameContent SET url='".$frame1."' WHERE name='frame1'";
$query = "UPDATE frameContent SET url='".$frame2."' WHERE name='frame2'";
$query = "UPDATE frameContent SET url='".$frame3."' WHERE name='frame3'";
$query = "UPDATE frameContent SET url='".$frame4."' WHERE name='frame4'";
mysqli_query($con,$query);
mysqli_close($con);
?>
I know that constantly setting the $query variable is causing problems but I'm not sure how else I can do this in the one page. Any help would be much appreciated.
Thanks!

First of all make sure the $queries are concatenated, then terminate each query with a semi-colon. After these you can use mysqli_multi_query to execute all four updates in one call from php.
$query = "UPDATE frameContent SET url='".$frame1."' WHERE name='frame1';";
$query .= "UPDATE frameContent SET url='".$frame2."' WHERE name='frame2';";
$query .= "UPDATE frameContent SET url='".$frame3."' WHERE name='frame3';";
$query .= "UPDATE frameContent SET url='".$frame4."' WHERE name='frame4';";
mysqli_multi_query($con,$query);

I think this might help :) but there's just a little changes within your codes:
<html>
<head>
<script src = "js/jquery-1.10.1.js"></script>
<script>
function updateDb()
{
// this var id will store all your 4 combobox values in an array
var id = [{val1: $("#frame1").val()},
{val1: $("#frame2").val()},
{val1: $("#frame3").val()},
{val1: $("#frame4").val()}];
//this .post will submit all data to db_submit.php
$.post("db_submit.php",{id:id}, function(data)
{
alert(data);
});
</script>
<?php
include 'db_connect.php';
?>
</head>
<body>
<select id="frame1" name="frame1">
<option value="">Select Channel</option>
<?php
$result = mysqli_query($con,"SELECT * FROM feedContent");
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['url'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
<select id="frame2" name="frame2">
<option value="">Select Channel</option>
<?php
$result = mysqli_query($con,"SELECT * FROM feedContent");
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['url'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
<select id="frame3" name="frame3">
<option value="">Select Channel</option>
<?php
$result = mysqli_query($con,"SELECT * FROM feedContent");
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['url'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
<select id="frame4" name="frame4">
<option value="">Select Channel</option>
<?php
$result = mysqli_query($con,"SELECT * FROM feedContent");
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['url'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
<input type="button" value="Submit" onClick="updateDb()"/>
</body>
<?php
mysqli_close($con);
?>
</html>
And in your DB_SUBMIT.PHP
<?php
include 'db_connect.php';
$frame1= mysqli_escape_String($_POST['id'][0]['val1']);
$frame2= mysqli_escape_String($_POST['id'][1]['val1']);
$frame3= mysqli_escape_String($_POST['id'][2]['val1']);
$frame4= mysqli_escape_String($_POST['id'][3]['val1']);
$query = mysqli_query("UPDATE frameContent SET url='$frame1' WHERE name='frame1'");
$query = mysqli_query("UPDATE frameContent SET url='$frame2' WHERE name='frame2'");
$query = mysqli_query("UPDATE frameContent SET url='$frame3' WHERE name='frame3'");
$query = mysqli_query("UPDATE frameContent SET url='$frame4' WHERE name='frame4'");
echo "Data was Successfully updated";
mysqli_close($con);
?>
I just add a button there for convenience, but if you dont want it just delete it and put back the onChange on every combocboxes that you have :)

Related

Get ID automatically in input-field after <SELECT> without button click

I have an SQL-database with many tables. Now I would like to create an input-form to be able to get data into the db without writing the entire sql-code every time. And this should work as follows:
All table names are listed in a drop-down menu. After having selected a table name, a new table with 4 columns is created automatically:
The first column of this table simply contains an increasing number.
The second column contains the field-names of the selected table.
In the third column there are empty input fields to enter the values for the database. Only in the third line (=product name) there is a drop-down menu with all product names from the main-table of the db.
The fourth column contains the data type (e.g. int or varchar)
All tables in the database have the same structure in the first 3 columns: the first column contains the table-id, the second column the foreign-key (=master_id) and the third column the product_name.
Up to this point, the script works well with the following 2 php-files (javasql.php and getuser.php):
javasql.php:
enter code here
<!DOCTYPE html>
<html>
<head>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="" class="optdrugs">please select</option>
<?php
include("files/zugriff.inc.php"); // database Access
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'product'";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<option class="optdrugs" value="'. $row['TABLE_NAME'] . '">' .
$row['TABLE_NAME']. '</option>';
echo '<br>';
}
?>
</select>
</form>
<br>
<div id="txtHint"><b>Bitte Tabelle auswählen:</b>
<br>
<?php
if (isset($_POST["submit"])) {
$sent = $_POST['sent'];
$q = $_POST['tablename'];
$column_passed = unserialize($_POST['column']); // content of array
$column is passed from getuser.php
foreach ($_POST["insertvalue"] as $key => $value) {
echo $value . "<br>";
$werte[] = "'$value'";
}
$sql="INSERT INTO $q ($column_passed) VALUES (" .
implode(", ", $werte) . ")"; // data entry
mysqli_query($db, $sql);
if (mysqli_affected_rows($db) > 0) {
echo "<h3 style='color:blue'>successful</h3>";
} else {
echo "<h3 style='color:red'>not
successful</h3>";
}
}
?>
</div>
</body>
</html>
enter code here
getuser.php:
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<form id="formdatabase" name="formdatabase" action="javasql.php"
method="post">
<input type="hidden" name="sent" value="yes">
<?php
$q = strval($_GET['q']);
$con = mysqli_connect('localhost','root','','product');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM $q";
$result = mysqli_query($con,$sql);
$numcols = mysqli_num_fields($result); // gets number of columns in result table
$field = mysqli_fetch_fields($result); // gets the column names from the result table
$data_type_array = array(
1=>'tinyint',
2=>'smallint',
3=>'int',
4=>'float',
5=>'double',
7=>'timestamp',
8=>'bigint',
9=>'mediumint',
10=>'date',
11=>'time',
12=>'datetime',
13=>'year',
16=>'bit',
252=>'text',
253=>'varchar',
254=>'char',
246=>'decimal'
);
$data_type_array = array_flip($data_type_array);
echo "<table>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th><th>" . 'Column names' . "</th>
<th>" . 'Values for db-entry' . "</th><th>" . 'Type' . "</th>";
echo "</tr>";
echo "<tr>";
$nr = 1;
for($x=0;$x<$numcols;$x++):?>
<td><?= $nr; ?></td>
<td><?= $field[$x]->name; ?></td>
<?= $column[] = $field[$x]->name; ?>
<td>
<?php
if ($field[$x]->name == 'Name') { // if-Beginn
?>
<select name="insertvalue[<?= $x; ?>]" id="insertvalue<?=
$x; ?>" size="1" onchange = "javascript:getSelectedRow()">
<?php
include("files/zugriff.inc.php");
$sql = "SELECT * FROM product_main ORDER BY Name";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<option class="optdrugs" value='. $row['Name'] . '>' .
$row['Name'] . '</option>';
echo '<br>';
}
?>
</select>
<?php
$name_option = "";
} else {
$name_option = "<input type='text' id='insertvalue" . $x . "'
name='insertvalue[" . $x . "]' size='50'>";
echo $name_option;
}
?>
</td>
<?php
$key = array_search($field[$x]->type, $data_type_array);
if($key !== false){
echo "<td>" . $key . "</td>";
}else{
echo "<td>" . $field[$x]->type . "</td>";
}
?>
<td><?= $field[$x]->type; ?></td>
<?= $nr = $nr + 1; ?>
</tr>
<?php endfor;
echo "</table>";
mysqli_close($con);
?>
<input type="hidden" name="tablename" value="<?= $q; ?>">
<input type="hidden" name="column" value="<?php echo htmlentities
(serialize($column)); ?>">
<input type="submit" value="Enter values" name="submit">
</form>
</body>
</html>
Since I need the master_id (= foreign key) in addition to the product-name for database entry, I would like to extend my script, so that the respective master_id is automatically sent to the input field in line 2, when a product-name is selected in line 3 ... without clicking a button. I tried to do this with javascript but it didn´t work. As far as I know, the solution would be to use AJAX but unfortunately, I am not very used to AJAX.
I would be more than happy, if someone could help me to solve this problem!

call php script Ajax way on form load and after submit button is clicked

I have a PHP form and gets loaded when the page is clicked. The php form has multiple inputs and the tABLE needs to be updated when the submit button is clicked.
I need to go to the Ajax way but I dont know how to call the php script after the form action is completed to reload the table. Any pointers will be helpful.
<form target="iframe_b" action="/php_src/srcsendMTdata.php" method="POST"
echo "sending data">
<fieldset>
Select SCEF:<br>
<?php
$dbuser = 'root';
$dbpass = 'xxxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ApplicationServer") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT SCEF_NAME FROM SCEF_DETAILS") or die(mysql_error());
echo "<select name='SCEF_Name' id='id_scefName'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['SCEF_NAME'] . "'>" . $row['SCEF_NAME'] . "</option>";
}
echo "</select>";
?>
<br><br>
<div>
<select name='takeaction' id="Actions" >
<option class='head'>Select Action</option>
<option value='Activate Devices'>Activate Devices</option>
<option value='Send MTData'>Send MTData</option>
<option value='Get MTData'>Get MTData</option>
</select>
<input type="submit" value="SUBMIT" name="submit_button">
<br><br>
<input type="text" id="id_mt_data" name="MT_data" value="MT DATA" style="display: none;" />
</div>
<br><br>
<table border="1">
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>External ID</th>
<th>Status</th>
</tr>
// This portion needs to be dynamic.(Below needs to be separate PHP script called via Ajax when the form is loaded and when the submit
button is pressed
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ApplicationServer") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT EXTERNAL_ID,CONNECTION_STATUS FROM DEVICE_DETAILS") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$extID = $row['EXTERNAL_ID'];
$conStatus = $row['CONNECTION_STATUS'];
echo "</tr><tr>";
echo "</td><td>";
echo "<input type=\"checkbox\" class=\"case\" name=\"checkBox[".$extID."]\" />";
echo "</td><td>";
echo "<input type=\"text\" class=\"classextID\" value=\"$extID\" name=\"textExID[".$extID."]\" />";
echo "</td><td>";
echo "<input type=\"text\" class=\"classConnection\" value=\"$conStatus\" name=\"textcon[".$extID."]\" />";
}
?>
</table>
</fieldset>
</form>

Jquery Variable in $('option[title= look]').show();

reviernummer.onchange = function(){
var look=$("#reviernummer").val();
$("option[class='sorted']").hide();
$("option[title=look]").show();
};
The php code :
<label style="width:100px;float:left;">für das Revier:*</label>
<select class="required" id="reviernummer" style="width:240px;" name="verhaltenscode" ' >
<?php
$selected = $arrayAktuellerDatensatz['verhaltenscode'];?>
<option selected ="selected" value="<?php echo $selected; ?>"><?php echo $selected; ?></option>
<?php loadselect('kataster', 'Fischereibuchzahl', 'Fischereibuchzahl'); ?>
</select><br />
<select class="required" id="verhaltenscode" style="width:240px;" name="verhaltenscode">
<?php $selected = $arrayAktuellerDatensatz['verhaltenscode_neu'];?>
<option selected ="selected" value="<?php echo $selected; ?>"><?php echo $selected; ?></option>
<?php loadselect('helpbrutstatus', 'Brutstatus', 'Brutstatus');?>
</select>
loadselect function :
if ($tblname == 'kataster'){
$query = "SELECT * FROM kataster";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$fieldvalue = $row['Fischereibuchzahl'];
$fieldcaption = $row['Fischereibuchzahl'];
$lat = $row['Benennung']?>
<option title="<?php echo $lat; ?>" value="<?php echo $fieldvalue;?>"><?php echo $fieldcaption .' | '.$lat?></option> <?php
}
}
else if ($tblname == 'helpbrutstatus'){
$query = "SELECT * FROM helpbrutstatus" ;
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$fieldvalue = $row['Fischereibuchzahl'];
$status = $row['Fischereibuchzahl'];
$fieldcaption = $row['Brutstatus']; ?>
<option value="<?php echo $fieldvalue;?>" title="<?php echo $status;?>" class="sorted">
<?php echo $status." | ".$fieldcaption?></option> <?php
}
}
I am trying to let all options disappear so i can make just some specific options be avaiable. What am i missing here in the last row of code? Can somebody help.
And sorry i couldn't find another answered question.
Thank you for your help.
You should concatenate String with variable using plus + signs, try the following code :
reviernummer.onchange = function(){
var look=$("#reviernummer").val();
$("option[class='sorted']").hide();
$("option[title='"+look+"']").show();
};
It will be better if you can use jquery on change event, try also :
$('#reviernummer').on('change', function(){
var look=$(this).val();
$("option[class='sorted']").hide();
$("option[title='"+look+"']").show();
};
Hope this helps.

how to put selected item in dropdown list

I am creating a dropdown list in php. how can i put the selected item when someone selects an item.
my php code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<select name="app" id="dropdown" value="" onchange="this.form.submit()" ><option>--select-app--</option>
<?php
$sql="select * from application";
$result=mysqli_query($con, $sql) or die("ereor selecting app ".mysqli_error($con));
while($row=mysqli_fetch_array($result))
{
$selected = $row['name'];
echo "<option id=". $row['id']."value = ".$row['id'].">".$row['name']."</option>";
}
echo "</select>";
?>
i want this: if I select an item it will show it as selected. how can I do this
You can do it in php like
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<select name="app" id="dropdown" value="" onchange="this.form.submit()" >
<option>--select-app--</option>
<?php
$sql="select * from application";
$result=mysqli_query($con, $sql) or die("ereor selecting app ".mysqli_error($con));
$selected_val = $_POST['app']; //Should be $_GET, $_POST, $_SESSION whatever your selected value is
while($row=mysqli_fetch_array($result))
{
if(trim($row['id']) == trim($selected_val)) //<== Change this line
$selected = 'selected="selected"';
else
$selected = '';
echo '<option id="'. $row['id'].'" value="'.$row['id'].'" '. $selected.'>'. $row['name'] .'</option>';
//^Change this line
}
echo "</select>";
?>
In jQuery you can do it like
$('#dropdown').val('<?php echo "My val"; //The value goes here ?>');
Assuming that you mean you want to retain the selection after the form is submitted, you can do this inside the while loop:
$selected = (isset($_POST['app']) && $_POST['app'] == $row['id'] ? 'selected' : '');
echo "<option id=".$row['id']." value = ".$row['id']." ".$selected.">".$row['name']."</option>";

Auto fill text box depending on Drop Down value

This might be a stupid question but I would like to have a clarification on how to go about this. I have come across quite a few articles that let to set the values of a text box depending on the choices made in a drop down menu using jQuery and Ajax. My issue is when I'm trying to do the same depending on the choices made in 5 drop down menus. I have the Id values stored in the database which should be used to populate the text box. Can anyone guide on how to go about this issue with multiple drop downs. This is my code so far:
<?php
$sql1="SELECT Schlungen FROM schulung as s";
$result=mysql_query($sql1);
echo "<p align='left'> <strong>Schulung 1</strong> <select name='Schlungen1'> <option value default></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['Schlungen'] . "'>" . $row['Schlungen'] . " </option>";
}
echo "</select>";
?>
<?php
error_reporting(0);
//Drop Down for Schulung 2
$sql2="SELECT Schlungen FROM schulung as s";
$result=mysql_query($sql2);
echo "<p align='left'> <strong>Schulung 2</strong> <select name='Schlungen2'> <option value default></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['Schlungen'] . "'>" . $row['Schlungen'] . " </option>";
}
echo "</select>";
?>
<?php
error_reporting(0);
//Drop Down for Schulung 3
$sql3="SELECT Schlungen FROM schulung as s";
$result=mysql_query($sql3);
echo "<p align='left'> <strong>Schulung 3</strong> <select name='Schlungen3'> <option value default></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['Schlungen'] . "'>" . $row['Schlungen'] . "</option>";
}
echo "</select>";
?>
<?php
error_reporting(0);
//Drop Down for Schulung 4
$sql4="SELECT Schlungen FROM schulung as s";
$result=mysql_query($sql4);
echo "<p align='left'> <strong>Schulung 4</strong> <select name='Schlungen4'><option value default></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['Schlungen'] . "'>" . $row['Schlungen'] . " </option>";
}
echo "</select>";
?>
<?php
error_reporting(0);
//Drop Down for Schulung 5
$sql5="SELECT Schlungen FROM schulung as s";
$result=mysql_query($sql5);
echo "<p align='left'> <strong>Schulung 5</strong> <select name='Schlungen5'><option value default></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['Schlungen'] . "'>" . $row['Schlungen'] . " </option>";
}
echo "</select>";
?>
<p align="left"><strong>Access_level </strong>
<input type="text" name="a_level" disabled="disabled">
</p>
For achieving auto completion,you can create a select field in html file,call a javascript function on keyup event and use jQuery for calling your php file
<html>
<head>
<script>
$('.autosuggest').keyup(function(){
$.post("<your file.php>",{any data you need},function(data){
//echo the data
//echo "<option value='" . $row['Schlungen'] . "'>" . //$row['Schlungen'] ." </option>";
$('.result').html(data)
});
});
$('.result option').click(function(){
var rValue = $(this).text();
$('.autosuggest').attr('value',rValue);
$('.result').html('');
});
</script>
</head>
<body>
<input type='text' class='autosuggest'/>
<select class='result'>
</select>
</body>
</html>
try to set the value of each html select option to be the id of that text
so the echo should be
echo "<option value='" . $row['id'] . "'>" . $row['Schlungen'] . " </option>";
then on the html select add the event onchange and add the JS function foo() to fill a hidden input with all selected ids by getting them from the page using the JQuery or Javascript
also you have to add id or class for each html select to get its selected value easily
$("#select1").val();
$("#select2").val(); ...
then insert these values in a hidden input field so the hidden input now contains all selected ids

Categories

Resources