I'm trying to insert a form in php statement like this
while($row = mysql_fetch_array($result))
{
echo "<form id='send' action='up.php' method='POST'>
<tr>
<td>" . $row['s_no'] ."</td>
<td> <label for='student_name'><textarea name='student_name' >".$row['student_name']."</textarea></label></td>
<td> <textarea name='roll_no'>".$row['roll_no']. "</textarea></td>
<td> <textarea name='company'>".$row['company']. "</textarea></td>
<td> <textarea name='contact_no' >".$row['contact_no']. "</textarea></td>
<td> <textarea name='email'>" .$row['email']. "</textarea></td>
</tr>
<input type='text' name='batch_name' disabled='disabled' size='7' value=" .$_POST['batch_name']. ">
<p align='center'><button id='submit' type='submit'>Update</button></p>
</form>";
}
I'have taken the datas from the database and put as default into the texareas and thus it cab de edited. So i planned to USE UDPDATE query to make the alternations like this:
<html>
<title>Alumini Update</title>
<head>
<?php
$con = mysql_connect("localhost","root","momsgift");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("alumini", $con);
mysql_query("UPDATE $_POST[batch_name] SET contact_no = $_POST[contact_no] WHERE roll_no = '2321'");
mysql_close($con);
?>
But while sending a query the data in the textarea doesnt loaded to the database ( BUt it redirects to the up.php page)
WHat may be the reason??
You are generating invalid HTML.
You cannot wrap a form around a table row without wrapping it around the entire table.
Your browser is error recovering by moving the form element. This is the most likely cause of the unexpected results.
Use a validator on your generated HTML.
In your MySQL update query you are only updating contact_no no other fields.
Also you have left your query open for SQL injections
$batch_number = mysql_real_escape_string($_POST['batch_name']);
$contact_no = mysql_real_escape_string($_POST['contact_no']);
$student_name = mysql_real_escape_string($_POST['student_name']);
$roll_no = mysql_real_escape_string($_POST['roll_no']);
$company = mysql_real_escape_string($_POST['company']);
$email = mysql_real_escape_string($_POST['email']);
mysql_query("UPDATE ('" . $batch_no. "')
SET contact_no = ('" . $contact_no . "'),
student_name = ('" . $student_name. "'),
company = ('" . $company . "'),
email = ('" . $email . "'),
WHERE roll_no = ('" . $roll_no . "')");
This (mysql_real_escape_string) won't solve every problem, and using PDO is a better method, but it's a very good stepping stone.
first write this and see the result,if it show's text of textarea it show's that text is sending in right way.and the problem is in ur sql code.
echo $_POST['contact_no'];
then you can echo the query and copy and run it in phpmyadmin and view error of sql.
//EXAMPLE 1
if (isset($_POST['update']))
{
$result = pg_query($db_con, "UPDATE mydbtable SET mydbrecord = '$_POST[my_var1]' WHERE mydbrecord_id = '$_POST[myfilterbyid_var]'");
if (!$result)
{
echo "Update failed!!";
}
else
{
echo "Update successfull!";
}
}
//EXAMPLE 2
<form name="display" action="" method="post">
<select name="mydropdown" action="test.php" method="post">
<?php
while($row = pg_fetch_assoc)
{
echo "<option id=\"{$row['result_var']}\">{$row['result_var']}</option>";
}
?>
</select>
Related
i am creating a form through php html and ajax that is specific for each row of a database table. I send the form data through ajax to another page which then takes that form data and uses it to pull data from another database based upon the results given and displays them.
I am fairly sure the problem is either with my select statement on the recipedisplay.php page or my syntax is wrong on how to echo out a returned variable.
select.php
<?php <script>
$('.button').click(function (e){
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'pages/recipes/recipedisplay.php',
data: $('#f'+id).serialize(),
success: function(d){
$('#infodisplay').html(d);
}
});
});
</script>
<div id=\"a".$row['id']."\">
<form id=\"f" . $row['id'] . "\">
<input type=\"hidden\" name=\"recipeid\" id=\"recipeid\" value=\"" . $row['id'] . "\">
<div id=\"reciperesultbutton\" class=\"button\"><div id=\"centering\">" . $row['name'] ." </div></div>
<div id=\"reciperesulttext\"> " . $row['id'] ." " . $row['longdesc'] ."</div>
</form>
<br>
</div>
";
}
?>
recipedisplay.php
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$id = mysqli_real_escape_string($con, $_POST['recipeid']);
$sql= "SELECT * FROM recipes WHERE 'id' ='".$id."'";
$row = mysqli_fetch_array($sql);
$name = $row['name'];
$longdesc = $row['longdesc'];
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
echo " fail ";
echo " . $name . ";
};
echo " . $id . ";
echo " work ";
echo " . $longdesc . ";
echo "$row[name]";
mysqli_close($con);
?>
The problem is in :
$row = mysqli_fetch_array($sql);
because mysqli_fetch_array() takes mysqli_query() result not your $sql query
So try to run your query first by this code :
mysqli_query($con,$sql);
$row = mysqli_fetch_array($mysqli_query);
Also you can use mysqli_fetch_assoc() that takes mysqli_query() too as a parameter
I'm new to ajax so I don't know much about ajax syntax. though i am trying here to pass variable from php to ajax and then back to php. I was able able to get it done with one variable when it came to two variables I was confused. I don't even know what to search on google to get an answer my to query. So I will be brief here's my php code. addnewbug.php
<script type="text/javascript" language="javascript" src="./javascripts/jquery.js"></script>
<script type="text/javascript" language="javascript" src="./javascripts/script.js"></script>
</head>
<div class="margin custom">
<body bgcolor="#2e2e2e">
<div style="text-align: center; padding-top: 0px">
<h1 style="color:white;font-size: 50px">Bughound</h1>
</div>
<div class="effect8">
<div class="tableMargin">
<table width="622" class="table">
<tr class="program_row">
<form>
<td width="150" class="td" style="padding-right: 1.9cm">Program</td>
<td width="171" class="td">
<select id="program" class="dropdown">
<option></option>
<?php
require "./db.php";
$sql = "SELECT DISTINCT program_name FROM program";
$result = db($sql);
while ($row = $result->fetch_assoc()) {
$program_name = $row['program_name'];
echo '<option name ="' . $program_name . '">' . $program_name . '</option>';
}
?>
</select>
</td>
<td width="51" class="td">Release</td>
<td width="41" >
<div class="release" id="release">
<select class="release_select" id='release1'>
</select>
</div>
</td>
<td width="103" class="td">Version</td>
<td width="78" class="td">
<div class="version" id="version">
<select class="version_select" id='program_number'>
</select>
</div>
</td>
</form>
</tr>
</table>
This is the original page where I'm trying to make changes in select box using the get passing statement
here's the script.js which I am using to get variable and pass it to another php program..
$(function(){
$("#program").change(function(){
$(".release_select").remove();
$(".version_select").remove();
if($("#program").val() !== "") {
$.get("addnewbug1.php", {program_name: $("#program").val()})
.done(function(data){
$("div.release").after(data);
});
$.get("addnewbug_version.php", {program_name: $("#program").val()})
.done(function(data){
$("div.version").after(data);
});
}
});
$("#program_number").change(function(){
$(".release_select").remove();
if($("#program_number").val() !== "") {
var val2 = $("#program_number").val();
$.get("addnewbug2.php?program_number="+val2, {program_name: $("#program").val()})
.done(function(data){
$("div.release").after(data);
});
}
});
});
The first function is working fine as it takes values from the program and pass it to addnewbug1.php which takes the program name and generate the new select boxes for release and version of it then which is replaced in div-release and division-version(or number)
this is the file where the first function work perfectly - addnewbug1.php
require "./db.php";
echo "<select class='release_select' id='release1'>";
$programname = $_GET['program_name'];
$sql1 = 'SELECT DISTINCT program_release FROM program WHERE program_name="'. $programname .'"';
$result1 = db($sql1);
while ($row1 = $result1->fetch_assoc()) {
$program_release = $row1['program_release'];
echo '<option name ="' . $program_release . '">' . $program_release . '</option>';
}
echo "</select>";
?>
Now I am having error in the second change function of script.js where I need to pass two variables in '$.get' area. Also the .change fucntion for program_number is not working and it won't delete the select box on changing it.
$.get("addnewbug2.php?program_number="+val2, {program_name: $("#program").val()})
and the addnewbug2.php is also the new file which is being used by it is -
require "./db.php";
echo "<select class='release_select' id='release1'><option></option>";
$programname = $_GET['program_name'];
$programnumber = $_GET['program_number'];
$sql1 = 'SELECT DISTINCT program_release FROM program WHERE program_name="'. $programname .'" and program_number=' . $programnumber;
$result1 = db($sql1);
while ($row1 = $result1->fetch_assoc()) {
$program_release = $row1['program_release'];
echo '<option name ="' . $program_release . '">' . $program_release . '</option>';
}
echo "</select>";
?>
I don't know if you get my question or not. Thank you for replying to this question and please reply if require more info.
this is the addidtional db.php code
function db($sql){
//Check for connection variable already set
if(!isset($conn)){
//Database Connectivity - ip, username, password, database name
$conn = new mysqli("i have filled this correctly");
}
//Check Connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, $sql);
mysqli_close($conn);
return($result);
}
If I get that correctly, your initial problem is to pass more than one variable in AJAX call.
You can construct the URL like this :
var val2 = $("#program_number").val();
var val1 = $("#program").val();
$.get("addnewbug2.php?program_number="+val2+"&program_name="+val1)
json_encode() is perfect for transport php variable with ajax
something like
//your ajax call receiver page -: your_link_for_ajax.php
$output = json_encode(array('type'=>'success','address'=>$address,'table_record'=>$table_record));
die($output);
you can read it like
this code on your html page
$.post('your_link_for_ajax', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="alert alert-danger">'+response.text+'</div>';
}else{
output = '<div class=" alert alert-success">'+response.address+'</div>';
$('#stateIdContact').html(response.table_record);
}
}, 'json');
Thank you for replying, i solved my problem using AngularJS, which i started reading after posting this question. My main moto behind this question was to populate a (2nd)select box and (3rd)select box using value from other (1st) select box and when the values in newly populate (2nd) select box was done. Then change values (3rd)select box using the (2nd) select box. Vice versa for last point. Apply unique filter to select boxes and without moving to next page.
So here's the code simplified form of Addnewbug.php-
<!DOCTYPE html>
<html >
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src= "https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.4/angular-filter.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<select ng-model="selectProgram">
<option></option>
<option ng-repeat="x in programes | unique: 'prognumber'" name=""{{x.progname}}"">{{ x.progname }}</option>
</select>
<select ng-model="selectNumber">
<option></option>
<option ng-repeat="x in programes | filterBy: ['progname']:selectProgram | filterBy: ['progrelease']:selectRelease | unique: 'prognumber'" name=""{{x.prognumber}}"">{{ x.prognumber }}</option>
</select>
<select ng-model="selectRelease">
<option></option>
<option ng-repeat="x in programes | filterBy: ['progname']:selectProgram | filterBy: ['prognumber']:selectNumber | unique: 'progrelease'" name=""{{x.progrelease}}"">{{ x.progrelease }}</option>
</select>
</div>
<script>
var app = angular.module('myApp', ['angular.filter']);
app.controller('customersCtrl', function($scope, $http) {
$http.get("db/program_db.php")
.success(function (response) {$scope.programes = response.records;});
});
</script>
</body>
</html>
offcourse i used some other stackexchange questions to get it right.
And for the table which is being imported in this code i used this program_db-
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
if(!isset($conn)){
//Database Connectivity - ip, username, password, database name
$conn = new mysqli("*connection parameters*");
}
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, "SELECT program_name, program_number,program_release FROM program");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"progname":"' . $rs["program_name"] . '",';
$outp .= '"prognumber":"' . $rs["program_number"] . '",';
$outp .= '"progrelease":"'. $rs["program_release"] . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
I have same problem as you had in this page: PHP ajax database : how to pass two variables and get data of them in different options? ,i have 2 diffrent php file,one is handling select files,the other handle the database sql,firstly i pass a value which user choosed from first select which updates the second select,and choosing second select should update third select(which is remain empty) i dont know what is my problem(i guess i send value of first ajax to the other php file,and when i get it back to use it for second ajax call,the first value will gone.
I am creating a form for inserting data which technologies are being used by which customers.
I get data of customer's ID and name and select a customer in an drop-down list, and i get data from technologies id and description and display description in a table + it creates a textbox (ID='box-". $row1['ID_T']."') for every technology entry in a DB.
So now i would like to check this dynamically created textboxes with jquery for value (if empty or filled with data) (getelementbyid) but i can not find a way to check theese DYN textboxes.
The ID_T and ID_C will be loaded into another table containing these two PK's and add string from textbox to value.
i would appreciate your help so much!
<HTML>
<HEAD>
<SCRIPT>
function update_tech(id,description)
{
var x = confirm('Do you want to edit technology '+description);
if (x == true)
{
document.getElementById('update_id').value = id;
//document.getElementById('description').value = description;
//document.form_update.submit();
}
}
</SCRIPT>
</HEAD>
<?php
include "connection.php";
$sql = "SELECT ID_C, Name FROM empresa";
$rs = mysql_query($sql, $conn);
$sql2 = "SELECT ID_T, description FROM technologies";
$rs2 = mysql_query($sql2, $conn);
while($row = mysql_fetch_array($rs2))
{
if (isset($_POST["box-".$row["ID_T"]]))
if ($_POST["box-".$row["ID_T"]] != "")
echo "INSERT ....".$_POST["box-".$row["ID_T"]]."<br>";
}
$rs2 = mysql_query($sql2, $conn);
mysql_close($conn);
?>
<BODY>
<SELECT NAME="customers" ONCHANGE="showCustomer(this.value)">
<?php
if (mysql_num_rows($rs))
{
while($row = mysql_fetch_array($rs))
{
?>
<option value='<?php echo $row['ID_C'] ?>'><?php echo $row['Name']?></option>
<?php
}
}
else {
echo "<option value=\"0\">No customers</option>";
}
?>
</SELECT>
<FORM METHOD="POST">
<?php
echo "<table border='0'>";
while($row1 = mysql_fetch_array($rs2))
{
echo "<tr>";
echo "<td><INPUT TYPE='text' name='box-". $row1['ID_T']."' ID='box-". $row1['ID_T']."'></td>";
echo "<td>" . $row1['description'] . "</td>";
echo "</tr>";
}
echo "</TABLE>";
?>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>
You can either maintain an array of input box ids or use the jquery partial selector to identify all the input boxes.
jQuery approach is something like:
$('input[id^="box-"]').each(function(e, i) { console.log(e); };
How to get my AJAX results from the input of a textbox populated from mysql live on the page.
I already got it to work with the use of textboxes, so if you check them then the page gets updated with the results of mysql.
The same I would like to use for my textboxes as soon as you type something in or select something from the autocomplete list (this would be even beter).
I have the following code that I want to use for the textbox:
HTML:
<input type="text" name="naam_klant" size="20" id="naam_klant" onkeyup="lookup(this.value);" onblur="fill();" >
<div class="suggestionsBox" id="suggestions" style="display: none;">
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
PHP:
$pdo = new PDO('mysql:host=localhost;dbname=records', 'root', '***');
$select = 'SELECT *';
$from = ' FROM overboekingen';
$where = ' WHERE FALSE';
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
if (in_array("naam_klant", $opts)){
$where .= " OR naam_klant = [$queryString%] ";
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
I am putting together a site that handles H&S memos, and I need members to confirm that they have read their memos. I have looked at ways of handling this and they are based on assuming that members have read the memos the last time they logged on. I can't use this method as I need to assure their company that their workers have read their safety memos.
I have tried various ways of doing this but none are working well enough.
The main problem is selecting the correct ID number for the memo that they have clicked that they have read and then updating the details to the memo_read table. Any pointers, workarounds or solutions much appreciated.
This is what I have so far:
<?php
$user_id = $user_data['user_id'] ;
$company_id = $user_data['company'];
$nothing = '';
$result1 = mysql_query ("SELECT `user`, `memo_id` FROM`memo_read` WHERE `user`= '$user_id '") or die(mysql_error());
$memo_id_query = '';
while($row = mysql_fetch_array($result1)){
$memo_id_query .= " AND `id`!= '".$row['memo_id']."'";
}
?>
<div id="memo">
<h7>These are your unread memos!</h7>
<table class="bit">
<thead><tr><th>Title</th><th>Author</th><th>Time/Date</th><th>Memo</th></tr></thead>
<?php
$result = mysql_query ("SELECT `id`, `memos`, `author`, `time`, `title` FROM `memo` WHERE `worker`= 1 AND `company`='$company_id' ".$memo_id_query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$memo = $row['memos'];
$author = $row['author'];
$time = $row['time'];
$title = $row['title'];
global $id;
?>
<tbody><tr><td><?php echo $title; ?></td>
<td><?php echo $author; ?></td>
<td><?php echo $time;?></td>
<td id="mem"><a class="toggle" href="#.bit" >read/hide</a>
<div class="hiddenDiv" ><?php echo $memo; ?><br>
<form id="tickmemo" action="" method="post">
<input type="submit" name="submit" value="mark as read">
</form>
</div></td></tr><tbody>
<?php
}
if (empty($_POST['submit']) === false) {
$q=("INSERT INTO `memo_read` VALUES ('$nothing', '$user_id', '$id') ");
$result = mysql_query($q) or die(mysql_error());
}
?></table></div>
(edit)
This is working great now i'll put it up here if anyone else needs it or if you can suggest any tweeks!
<?php
$user_id = $user_data['user_id'] ;
$company_id = $user_data['company'];
$nothing = '';
$result1 = mysql_query ("SELECT `user`, `memo_id` FROM`memo_read` WHERE `user`= '$user_id '") or die(mysql_error());
$memo_id_query = '';
while($row = mysql_fetch_array($result1)){
$memo_id_query .= " AND `id`!= '".$row['memo_id']."'";
}
if (isset($_GET['success']) && empty($_GET['success'])) {
echo 'You have marked that memo as read!<br>We will send you back in 3 seconds!';
header("Refresh: 3; url=\"http://www.testbed1.tk/login/index.php\"");
} else {
?>
<div id="memo">
<h7>These are your unread memos!</h7>
<table class="bit">
<thead><tr><th>Title</th><th>Author</th><th>Time/Date</th><th>Memo</th></tr></thead>
<?php
$result = mysql_query ("SELECT `id`, `memos`, `author`, `time`, `title` FROM `memo` WHERE `worker`= 1 AND `company`= '$company_id' ".$memo_id_query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$memo = $row['memos'];
$author = $row['author'];
$time = $row['time'];
$title = $row['title'];
?>
<tbody><tr><td><?php echo $title; ?></td>
<td><?php echo $author; ?></td>
<td><?php echo $time;?></td>
<td id="mem"><a class="toggle" href="#.bit" >read/hide</a>
<div class="hiddenDiv" ><?php echo $memo; ?><br>
<form id="tickmemo" action="#" method="post">
<input type="hidden" name="id" value="<?php echo $id;?>" />
<input type="submit" name="submit" value="mark as read">
</form>
</div></td></tr><tbody>
<?php
}
$id = $_POST['id'];
if (empty($_POST['id']) === false) {
$q=("INSERT INTO `memo_read` VALUES (''".mysql_real_escape_string($nothing)."'','".mysql_real_escape_string($user_id)."','".mysql_real_escape_string($id)."') ");
$result = mysql_query($q) or die(mysql_error());
header('Location: worker.php?success');
}
?></table></div>
<?php } ?>
There is a wide range of aspects here to comment on:
You have no input field "id" in your form, hence someone submitting the form cannot communicate what id they want to mark as read
You are assuming that register globals is on for the variable $id to be filled with a value. Instead use $_POST['id']
Your database queries lend themselves to SQL injection attacks, as you don't check any input. Use at least intval($_POST['id']) when saving to the database
mysql_query will be turned off in PHP5.5 I think, move to PDO
There is nothing wrong with doing it all in one file, but good programming style is to put the action logic at the top, output at the bottom.
If you need to scale the "read" table to a couple of 100000 rows, use this
I think the business case is flawed as well. It will probably lead to people clicking memos as read, in the best case have them actually read, but not understood and memorized. It may be better to create a peer-to-peer quiz system to memorize the memos.
Your application flow it's not really clear. You should have:
A page where you list the unread memo to the user. Every list item should have a link that points to memo description page.
Memo description page - in this page you actually insert in memo_read table the user_id and memo_id which has been read.