How to Insert to database from loop Using PHP? - php

The problem occurs when I insert without data. So I want your help in solving this problem.
This is my file:
students.php
<form id="student_form" method="POST" action="">
<?php
if(mysql_num_rows($q)>0){
?>
<table border="0" dir="ltr" align="center"cellpadding='0' cellspacing='0' >
<tr> <th>Student ID</th><th>Name</th><th>AVG</th><th>Joining Year</th><th>Message</th><th>Sending Message</th> </tr>
<?php while($row = mysql_fetch_array($q)){ ?>
<tr>
<td id="stud_id[]"> <?php echo $row['studant_ID']; ?></td>
<td> <?php echo $row['studant_Name']; ?></td>
<td> <?php echo $row['Average']; ?></td>
<td> <?php echo $row['year']; ?></td>
<td> <input id="message1[]" name="message1[]" type="text" size="25px" /></td>
<td><input name="submit[]" id="submit[]" type="submit" value="Send" /> </td>
</tr>
<?php }}
and this is my insert file:
insert_message.php
if (isset($_POST['message1']) && $_POST['message1']!='') {
$addss = mysql_real_escape_string($_POST['message1']);
}
if (isset($_POST['stud_id']) && $_POST['stud_id']!='') {
$std_id = mysql_real_escape_string($_POST['stud_id']);
}
//#######################################################################
$query1 = "INSERT INTO `message` (`rcvrid`, `senderid`, `msg`) VALUES ('$std_id', '22011111', '$addss'); ";
mysql_query($query1);
I connect between two file by jquery and ajax.
<script>
$("#student_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "insert_message.php",
data: $(this).serialize(),
success: function(data) {
$("#inner_contant").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
</script>

Remove the form from the page
<tr>
<td id="stud_id"> <?php echo $row['studant_ID']; ?>
<input type="hidden" name="stud_id" value="<?php echo $row['studant_ID']; ?>"/>
</td>
<td> <?php echo $row['studant_Name']; ?></td>
<td> <?php echo $row['Average']; ?></td>
<td> <?php echo $row['year']; ?></td>
<td> <input id="message1" name="message1" type="text" size="25px" /></td>
<td><button class="submit" type="submit" />Send </button> </td>
</tr>
second:
your js should look like this:
$(".submit").on("click", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "insert_message.php",
data: {stud_id:$(this).closest('tr').find('input[name="stud_id"]').val(),message1:$(this).closest('tr').find('input[name="message1"]').val()},
success: function(data) {
$("#inner_contant").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
In insert_message.php
you need to echo a message to see if you where succesful in updating the database
echo json_encode(array('message'=>'Data updated/Error'));

First of all - all data passed to server in a $_POST array is taken from input fields with name attribute (unless you have some custom js handlers).
So
<td id="stud_id[]"> <?php echo $row['studant_ID']; ?></td>
does nothing.
If you want to store studant_ID somehow - use hidden field for example:
<td>
<input type="hidden" name="stud_id[]" value="<?php echo $row['studant_ID']; ?>" />
</td>
Next - what do you want from this buttons:
<input name="submit[]" id="submit[]" type="submit" value="Send" />
As they are all belong to one form they will do the same - send all fields to server. If you want every submit button send to server only a pair student_id, message you have to create a form for each pair (or do some js-handlers). Otherwise, on your server you'll have:
$_POST['stud_id'] array of all students ids from form
$_POST['message1'] array of all messages from form
If you want to process them all - do a foreach:
foreach ($_POST['stud_id'] as $key => $id) {
// find the message
$msg = $_POST['message1'][$key];
$query1 = "INSERT INTO `message` (`rcvrid`, `senderid`, `msg`) VALUES ('$id', '22011111', '$msg'); ";
mysql_query($query1);
}
And of course you should remove mysql_ functions and use newer apis - PDO or mysqli

Related

Ajax Posted data not being read by $_POST in php

I am trying to post the value of fields in a table through Ajax to process.php that will process the data.
the table:
<form name="items">
<table width="90%" border="1">
<tbody>
<tr>
<td width="26%">Item Name</td>
<td width="22%">If other then give name</td>
<td width="22%">Quantity</td>
<td width="16%">$/Unit</td>
<td width="14%">Total</td>
</tr>
<?php for ($i = 1; $i <= 10; $i++) {
?>
<tr>
<td>
<select name='itemname<?php echo $i;?>' id='itemname<?php echo $i;?>'>
<option value="other">other</option>
<?php
$qry_item_name = "SELECT DISTINCT item_name FROM bus_name_details";
$result_item_name = mysql_query($qry_item_name);
while($row_item_name = mysql_fetch_array($result_item_name)) {
$option .="<option>" . $row_item_name['item_name'] . "</option>";
echo $option;
}
?>
</select>
</td>
<td>
<input type="text" name="other<?php echo $i;?>" id="other<?php echo $i;?>"></td>
<td>
<input type="text" name="quan<?php echo $i;?>" id="quan<?php echo $i;?>" value="0"></td>
<td><input type="text" name="unit<?php echo $i;?>" id="unit<?php echo $i;?>" onkeyup="calculateTotal('<?php echo $i;?>')"></td>
<td><span name="total<?php echo $i;?>" id="total<?php echo $i;?>"></span></td>
</tr>
<?php }?>
</tbody>
</table>
</form>
<span id="subm3" class="subm3" >Submit </span>
The Ajax:
<script>
$(document).on('click', '.subm3', function() {
var datas = {};
for ($i = 1; $i < 2; $i++) {
// drop down list of items
datas["item_name"+$i]= $('#itemname'+$i+' option:selected').attr('value')
// other name
datas["other"+$i]= $('input[name=other'+$i+']').val()
// quantity
datas["quan"+$i]= $('input[name=quan'+$i+']').val()
// price per unit
datas["unit"+$i]= $('input[name=unit'+$i+']').val()
}
$i = $i_limit-1;
$.ajax({
url: 'parts/process.php?order=3&items='+$i,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(datas)
});
});
</script>
then the process :
<?php
if ($order==3){
$loop = $_GET[items];
$other1= $_POST["other1"];
echo "other1 = ".$other1;
}
?>
On chrome inspector i get that the data was sent like this as source :
{"item_name1":"other","other1":"Water Valve","quan1":"2","unit1":"2"}
and like this as parsed :
item_name1: "other"
other1: "Water Valve"
quan1: "2"
unit1: "2"
but the response from process.php (the one that got the values) seems to only have read the get values but not the post values :
other1 =
i am pretty much new to ajax and hope someone could help point me to where i am going wrong here. This might not even be the easiest or best way of doing what i am trying to do, but it kind of makes sense to my brain at the moment so i am taking this route. Any help is appreciated
can you try data:datas insted of data: JSON.stringify(datas) in ajax request
ref: how to send multiple data with $.ajax() jquery

Looping through serialized data to insert updates to MySQL DB

Thanks to the help below, I switched my code to use serlize(), but I am still having a similar problem of only getting the latest row sent, here is what I am doing now
<form id="test_table">
<table>
<thead>
<tr>
<th> ID </th>
<th> col2 </th>
<th> col3 </th>
</tr>
</thead>
<tbody><!--table body-->
<form id="form_x">
<tr>
<td> <input type="text" name="col1" default value="1"> </td>
<td> <input type="text" name="col2" default value="cat"> </td>
<td> <input type="text" name="col3" default value="dog"> </td>
</tr>
<tr>
<td> <input type="text" name="col1" default value="2"> </td>
<td> <input type="text" name="col2" default value="fish"> </td>
<td> <input type="text" name="col3" default value="rabbit"> </td>
</tr>
</tbody>
</table>
</form>
<button class="btn btn-primary" value="test_table" onclick="update(this.value)">Update</button>
<p><tt id="results"></tt></p>
<script>
function update(form_name){
var str = $( test_table ).serialize();
$( "#results" ).text( str );
$.ajax({
type: "POST",
url: "/site/pages/update.php",
data: $( "#"+form_name ).serialize(),
success : function(res){ console.log(res); }
});
}
</script>
I can see the serialized data being captured i.e.,
col1=1&col2=cat&col3=dog&col1=2&col2=fish&col3=rabbit
But when I dump what is being passed, it is only seeing the last row value
update.php
<?php var_dump($_POST); ?>
Result:
array(3) {
["col1"]=>
string(1) "2"
["col2"]=>
string(4) "fish"
["col3"]=>
string(6) "rabbit"
}
Can anyone direct me to some advice to fix my update.php page to loop through the POST data? I want to update the database row from each id of that row e.g.
//setup loop
$sql = "UPDATE Table SET
col2 ='".$_POST["col2"]."',
col3 ='".$_POST["col2"]."',
WHERE id='".$_POST["col1"]."' ";
i.e.,
$sql = "UPDATE table SET
col2='cat' , col3='dog'
WHERE id=1";
$sql = "UPDATE table SET
col2='fish' , col3='rabbit'
WHERE id=2";
===========================================================================
Old Question:
I am trying to enable a user to edit a dynamically created row (with user based inputs in TDs) that send and update on click of an update button, I can see the inputs are being captured correctly, but cannot work out how to update the database from the ajax call, here's the (abridged) code:
form_page.php
<table id="table_name">
<thead>
<tr>
<th>ID</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
The phpcode associated with generating the table rows:
<?php
echo '<form id="" method="POST" action="" >';
$sql= "SELECT * FROM tablename";
$stmt= $conn->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $row) {
echo '<td>';
echo 'ItemID_'.$row['ID'].'';
echo '</td>';
echo '<td>';
echo ' <input class="update_value" type="text" id="ItemID_'.$row['ID'].'" default value="'.$row['col2'].'">';
echo '</td>';
echo ' <input class="update_value" type="text" id="ItemID_'.$row['ID'].'" default value="'.$row['col3'].'">';
echo '</td>';
echo'</tr'>;
}
?>
<button type="button" id="update_button">Update</button>
</form>
</table>
Result with editable col 2/3:
ID | col2 | col3
1 | lorem (editable) | ipsum (editable)
2 | dolor (editable) | sit amet (editable)
Update (Button)
With the code looking something like:
<table id="table_name">
<thead>
<tr>
<th>ID</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
</thead>
<tbody>
<form id="" method="POST" action="">
<tr>
<td>
ItemID_1
</td>
<td> <input class="update_value" type="text" id="ItemID_1" default value="lorem">
</td>
<td> <input class="update_value" type="text" id="ItemID_2" default value="ipsum">
</td>
</tr>
</tbody>
<button type="button" id="update_button">Update</button>
Here's the ajax I am using to send it to the update page
<script>
$(document).ready(function(){
$("#update_button").click(function(e) {
e.preventDefault();
var values = {};
$('input.update_value').each(function(n, user_input){
values[ $(user_input).attr('id') ] = $(user_input).val();
//used to test and make sure its passing id vals to values
//alert(JSON.stringify(values, null, 4));
});
$.ajax({
type: "POST",
url: "/site/pages/update.php",
data: { updatefrominputs: values }
});
});
});
</script>
With the alert above (used for testing) showing:
localhost says
{
"ItemID_1": "lorem"
"ItemID_1": "ipsum"
}
OK so far, but then on another click it over writes the "lorem"
localhost says
{
"ItemID_1": "ipsum"
"ItemID_2": "dolor"
}
This is the first problem, it has over written the "lorem" value to send across
Here is the second problem and where I am currently stuck, sending and updating the database
I can see that the ajax is being posted by adding this to the ajax:
success: function (data) {
alert("sent");
}
The update.php file code:
<? php
include connect.php //database connection script (don't think I need to call it)
foreach($_POST['updatefrominputs'] as $id=>$value)
$sqlQuery = "UPDATE tablename SET
//col2=col2inputvalue
//col3=col3inputvalue
WHERE
//col1id=the NUMBER without the ID_part?
";
$sqlQueryStmt = $conn->prepare($sqlQuery);
$sqlQueryStmt->execute();
?>
The problem I have is that I cannot seem to get it to update the database, I am not sure on how to fill out the UPDATE clause below. Also, it doesn't even feel like it posts to this page, but the success function says it does??
Also, how would I just get the number to use in the WHERE clause? I can edit the code above to just give me the ID number and then use col1ID=col1passedID but I would end up with duplicate ID's if I use this process across more than one form (on the same page). e.g.
<form 1>
foreach ($results1 as $row1) {
echo ' <input class="update_value" type="text" id="'.$row1['ID'].'" default value="'.$row['col2'].'">';
}
</form 1>
<form 2>
foreach ($results2 as $row2) {
echo ' <input class="update_value" type="text" id="'.$row2['ID'].'" default value="'.$row2['col2'].'">';
}
</form 2>
Would output:
<form 1>
<input class="update_value" type="text" id="1" default value="lorem">
</form 1>
<form 2>
<input class="update_value" type="text" id="1" default value="ipsum">
</form 2>
One solution I can think of would be to send the ajax like this:
var updatedetals= {
id: $("#ItemID_1").val(),
col1: $("#col2").val(),
col2: $("#col2").val()
}
$.ajax({
type: "POST",
url: "/site/pages/update.php",
data:updatedetals,
dataType: 'JSON',
success: function(JSON){
refreshResults();
}
});
But this won't give me unique IDs either, and I would have to do a ajax call for every row?
Is there a better way to iterate over every uniquely generated row, get the TD input values and send those updated values to the database?
You need to use name="col1[]" in your html this would send all values in an array. Because you have multiple inputs with the same name php by default gets the last one. if you add [] you can fetch values like $_POST["col1"][0] and such.
Then you can also loop over the values like
for($i=0;$i<count($_POST["col1"]);$i++){
$col1 = $_POST["col1"][$i];
$col2 = $_POST["col2"][$i];
$col3 = $_POST["col3"][$i];
//use the variables in update query
}
The problem is that your columns have duplicate names but $POST requires unique keys for values. So you get 3 keys only: col1, col2, and col3... and the values get overwritten, so you're left with only the last row's values.
If you want to collect all the rows, then you should give each a unique name. E.g.
<form id="test_table">
<table>
<thead>
<tr>
<th> ID </th>
<th> col2 </th>
<th> col3 </th>
</tr>
</thead>
<tbody><!--table body-->
<form id="form_x">
<tr>
<td> <input type="text" name="row1_col1" default value="1"> </td>
<td> <input type="text" name="row1_col2" default value="cat"> </td>
<td> <input type="text" name="row1_col3" default value="dog"> </td>
</tr>
<tr>
<td> <input type="text" name="row2_col1" default value="2"> </td>
<td> <input type="text" name="row2_col2" default value="fish"> </td>
<td> <input type="text" name="row2_col3" default value="rabbit"> </td>
</tr>
</tbody>
</table>
</form>
<button class="btn btn-primary" value="test_table" onclick="update(this.value)">Update</button>
<p><tt id="results"></tt></p>
<script>
function update(form_name){
var str = $( test_table ).serialize();
$( "#results" ).text( str );
$.ajax({
type: "POST",
url: "/site/pages/update.php",
data: $( "#"+form_name ).serialize(),
success : function(res){ console.log(res); }
});
}
</script>
Try it. This will give you six values in your php $POST.
Then you can iterate over them and extract the col name using some string slicing techniques, like split or substr.

php check text input length and change another input based on length

I have an php form utilizing several inputs that is driving a kiosk page. If a text input is blank I want this update a separate input with the word "hidden" If there is text I would like the word "visible" to show. Currently my code works if you click submit twice but will not work on the first submit. Here is my current code:
The if function that is current working on second submit:
if (strlen($something)>0) {
$_POST['someone'] = "visible";
} else {
$_POST['someone'] = "hidden";
}
input form:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td>something : </td>
<td><input type="text" id="something" name="something" value="<?php echo htmlspecialchars($something); ?>"/></td>
<td></td>
</tr>
<tr>
<td></td>
<td><?php echo $_SERVER['PHP_SELF']; ?></td>
<td></td>
</tr>
<tr>
<td>someone:</td>
<td><input type="text" id="someone" name="someone" value="<?php echo htmlspecialchars($someone); ?>"/></td>
<td></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name='submit' value="Submit"/></td>
<td></td>
</tr>
</table>
</form>
Here is the update code:
$usql = "UPDATE test SET something= '".$_POST['something']."', someone= '". $someone ."' WHERE ID='a';";
Currently the "someone" input has a display of none so it cannot be seen by the user. This is not necessary but if someone could tell me how to bypass adding an input altogether and tweak the update statement itself to update something that would be great as well! Thanks!
Any help would be appreciated!
Using session variables can save the page state, even after reload.
First page save:
session_start();
$_SESSION['someone'] = $_POST['someone'];
Then:
if(isset($_SESSION['someone']))
{
if (strlen($_SESSION['someone'])>0) {
$_POST['someone'] = "visible";
} else {
$_POST['someone'] = "hidden";
}
}

PHP Passing Input values through href to another page

<input type="text" name="a" id="a" />
CLICK
Now this is my question that can we pass an input tag value of HTML to 'mk' so that value can be used in the next page for process.
Though i have done my project in a different way but still i want to know wether is it possible to do so .
I have searched a lot but none of the question is same as i got so plz help me out.
And i dnt want to use form so i just want to know can we pass this value using href tag r not.
This is the code i have
<form method="post">
<table align="center" bgcolor="#FFFFCC" border="1">
<tr><th>ID</th><th>PRODUCT</th><th>PRICE</th><th>DATE OF POST</th><th>PHONE NUMBER</th><th>AUTHENTICATE</th></tr>
<?
$sel = mysql_query("SELECT * FROM addunauth WHERE adminauthorize = 'uncheck'") or die("CANNOT FETCH DATA FOR ADMIN " . mysql_error());
if (mysql_num_rows($sel) > 0) {
while ($data = mysql_fetch_array($sel)) {
?> <tr>
<td><? echo $data['id']; ?></td>
<td><? echo $data['product_name']; ?></td>
<td><? echo $data['product_sp']; ?></td>
<td><? echo $data['product_time']; ?></td>
<td><? echo $data['phoneNumber']; ?></td>
<td><input type="text" name="a" id="a" /></td>
<td align="center">
<a href="processadminTask.php?id=<? echo $data['id']; ?>&mk=" >
AUTHENTICATE
</a>
</td>
</tr>
<?
}
} else {
?> <tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>
<? }
?>
</table>
</form>
Now just tell me how to pass the input value
Your variable not parse inside single quotes. your <? echo '$data['id']' ?> should be <?php echo $data['id'] ?>
<input type="text" name="a" id="a" />
CLICK"
<a id="link" href="xxx.php?id=111&mk=">CLICK</a>
Edit:-
simply add one more hidden fields to store id value as well and get value in js and assign to href
<input type="text" name="idval" id="idval" value="100" />
<input type="hidden" name="mk" id="mkval" value="101" />
Js:-
var idval = $('#idval').val();
var mk = $('#mkval').val();
var link = 'xxx.php?id=' + idval + '&mk=' + mk;
$("#link").attr("href", link);
Working Demo
<? echo '$data['id']' ?>
Is wrong PHP Syntax
Use
<?php echo $data['id']; ?>
Like:
CLICK
Your
<? echo '$data['id']' ?>
is not correct. You can actually use something like this
<?= $data['id'] ?>
so you'll have
CLICK"
I think it is possible with javascript:
getElementById('id of html input').value
This will get you the input value and then you can assign it to 'mk'
So you can check with it
Try this
<?php
$data['id'] = 2;
?>
<html>
<input type="text" name="a" id="a" />
CLICK
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script >
$(document).ready(function(){
$('a[href]').click(function(event){
event.preventDefault();
event.stopPropagation();
var inputTagID = $('#a').val();
var hrefVal = this.toString().replace("&mk=", "&mk="+inputTagID);
window.location = hrefVal;
});
});
</script>
</html>

.find() jQuery not working in tables

<tr id="<?php echo $id?>">
<input type="hidden" value="<?php echo $id?>"/>
<td> <?php echo $id;?> </td>
<td id="fname"> <?php echo $firstname[$key];?> </td>
<td id="lname"> <?php echo $lastname[$key];?> </td>
<td id="tage"> <?php echo $age[$key];?> </td>
</tr>
jQuery:
$('.edit').click (function(){
var id = $(this).parent().data('id');
var fname = $('#id').find('#fname');
alert(fname);
});
Want to get the text inside <td>
In alert it returns an object.
What am I doing wrong?
You are using a string instead of an jquery object for your selector.
$(id).find('#fname')
You might consider this, if the value you're retrieving is that of an id, so it will need the hash to be a valid selector:
$('#' + id).find('#fname')
Also, valid markup requires id's to be unique on the page.

Categories