MySQL php edition table and adding the same value on another table - php

I actually developping an intranet solution for my work,
The thing is that i want to update and operation and add the same result into one of my 3 different tables depending on the -operation- option,
in my initial code if the modification is ok the data will be updated into "taches_redaction" table,
in revenche i need to add 3 different rules,
soif operation is equal to 1 up date taches_redction and add the data into copie table,
soif operation is equal to 2 up date taches_redction and add the data into colla table,
soif operation is equal to 3 up date taches_redction and add the data into archive table,
all of this to have a precise historical record on echa changes in my operations and have some values to get statistics for each team member on the company...
<?php
include '../theme/header-global.php';
?>
<?php
/*
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($serie, $user_id, $journee, $titre, $region, $role, $operation, $date, $error)
{
?>
<div style="width:100%">
<center><h1>تحيين التوزيع</h1></center>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="serie" value="<?php echo $serie; ?>" readonly="readonly" />
<table cellpadding="3" cellpadding="3" align="center" id=MyTable width="650">
<tr>
<td align="center">الإسم</td>
<td align="center">
<?php
// get results from database
$usage = mysql_query("SELECT t.* , o.* FROM users t,taches_redaction o WHERE t.id=o.user_id GROUP BY user_name")
or die(mysql_error());
while($row = mysql_fetch_assoc( $usage )) {
if($row['user_id'] == $user_id)
{ // echo out the contents of each row into a table
echo '' . $row['user_name'] . '';
} else {
// do something else
echo '';
}
}
?>
</td>
<td>
<select id="user_id" name="user_id">
<option value="0"></option>
<?php
$sql = mysql_query('SELECT * FROM users');
while($row = mysql_fetch_array($sql)){
if($row['id'] == $user_id)
{
echo '<option value=' . $row['id'] . ' selected=selected>' . $row['user_name'] . '</option>';
} else {
// do something else
echo '<option value=' . $row['id'] . '>' . $row['user_name'] . '</option>';
}
}
?>
</select>
</td>
</tr>
<tr>
<td align="center">اليومية</td>
<td align="center"><input type="text" name="journee" value="<?php echo $journee; ?>" /></td>
<td></td>
</tr>
<tr>
<td align="center">الرسم العقاري</td>
<td align="center">
<input type="text" name="titre" value="<?php echo $titre; ?>" />
<?php if (!empty($region) && $region == '4' ) echo 'FR'; ?>
<?php if (!empty($region) && $region == '1') echo 'بن عروس'; ?>
<?php if (!empty($region) && $region == '2') echo 'زغوان'; ?>
<?php if (!empty($region) && $region == '3') echo 'تونس'; ?>
</td>
<td>
<select name="region">
<option value="4" <?php if (!empty($region) && $region == '4' ) echo 'selected = "selected"'; ?>>FR</option>
<option value="1" <?php if (!empty($region) && $region == '1') echo 'selected = "selected"'; ?>>بن عروس</option>
<option value="2" <?php if (!empty($region) && $region == '2') echo 'selected = "selected"'; ?>>زغوان</option>
<option value="3" <?php if (!empty($region) && $region == '3') echo 'selected = "selected"'; ?>>تونس</option>
</select>
</td>
</tr>
<tr>
<td align="center">المهام</td>
<td align="center">
<select id="role" name="role">
<option value="0"></option>
<option></option>
</select>
</td>
<td>
</td>
</tr>
<tr>
<td align="center">العملية</td>
<td align="center">
<?php
$fonki = mysql_query("SELECT * FROM fonctions")
or die(mysql_error());
// get results from database
$operage = mysql_query("SELECT t.* , o.* FROM taches_redaction t,operations o WHERE t.operation=o.oper_id GROUP BY operation")
or die(mysql_error());
// display data in table
/* echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>"; */
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_assoc( $operage )) {
if($row['oper_id'] == $operation)
{ // echo out the contents of each row into a table
echo '' . $row['operation_name'] . '';
} else {
// do something else
echo '';
}
}
?>
</td>
<?php
echo "<td>
<select name=operation>
<option value =0></option>";
include "../render/render_operation-selected.php";
echo "</select>
</td>";
?>
</tr>
<tr>
<td>تاريخ التحيين</td>
<td>
<?php
echo '' . $row['date'] . '';
?>
</td>
<td style="direction:rtl;">
<?php echo "<input type='text' value='".date('o/m/d')."' style='width: 148px;' name='date' readonly=readonly>";?>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="تغيير" class="brd"></td>
<td align="center">
<input type="submit" value="إلغاء" onClick="history.go(-1);return true;" class="bbl">
</td>
</tr>
</table>
<?php
}
// connect to the database
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['serie']))
{
// get form data, making sure it is valid
$serie = $_POST['serie'];
$user_id = mysql_real_escape_string(htmlspecialchars($_POST['user_id']));
$journee = mysql_real_escape_string(htmlspecialchars($_POST['journee']));
$titre = mysql_real_escape_string(htmlspecialchars($_POST['titre']));
$region = mysql_real_escape_string(htmlspecialchars($_POST['region']));
$role = mysql_real_escape_string(htmlspecialchars($_POST['role']));
$operation = mysql_real_escape_string(htmlspecialchars($_POST['operation']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
// check that firstname/lastname fields are both filled in
if ($user_id == '' || $journee == '' || $titre == '' || $region == '' || $role == '' || $operation =='' || $date =='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($serie, $user_id, $journee, $titre, $region, $role , $operation, $date, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE taches_redaction SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date' WHERE serie='$serie'")
/* frere update */
/*
AND
mysql_query("INSERT copie SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date'")
AND
mysql_query("INSERT colla SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date'")
AND
mysql_query("INSERT archive SET user_id='$user_id', journee='$journee', titre='$titre', region='$region', role='$role', operation='$operation', date='$date'")
*/
or die(mysql_error());
// once saved, redirect back to the view page
/* header('Refresh: 2; URL = taches_view.php');
*/
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['serie']) && is_numeric($_GET['serie']) && $_GET['serie'] > 0)
{
// query db
$serie = $_GET['serie'];
$result = mysql_query("SELECT * FROM taches_redaction WHERE serie=$serie")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$serie = $row['serie'];
$user_id = $row['user_id'];
$journee = $row['journee'];
$titre = $row['titre'];
$region = $row['region'];
$role = $row['role'];
$operation = $row['operation'];
$date = $row['date'];
// show form
renderForm($serie, $user_id, $journee, $titre, $region, $role, $operation, $date, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
<!-- end .content --></div>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<?php
include '../theme/footer-global.php';
?>

Related

Multiple Choice Quiz - not updating responses

I have a form that outputs:
Quiz_Assign_ID (Combines User_ID with Quiz ID)
Question ID
Checkboxes for inputting the response (Option A, Option B, Option C)
<div class="Main">
<form method="post" action="LP_Quiz_Student_Quiz_Responses.php">
<?php
$quiz_id = trim($_GET['quiz_id']);
$quiz_assign_id = trim($_GET['quiz_assign_id']);
$i = 1;
$count=1;
$sel_query=("SELECT Quiz.quiz_id, Quiz.quiz_title, Quiz_Questions.quiz_id, Quiz_Questions.quiz_question_id, Quiz_Questions.question, Quiz_Questions.option1, Quiz_Questions.option2, Quiz_Questions.option3, Quiz_Questions.answer FROM Quiz, Quiz_Questions WHERE (Quiz.quiz_id=Quiz_Questions.quiz_id) and (Quiz.quiz_id=?)");
$stmt = $conn->prepare($sel_query);
$stmt->bind_param("i", $quiz_id);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
if($result->num_rows === 0) exit('No Quiz Questions!');
while($row = $result->fetch_assoc()) { ?>
<p></p>
<p> </p>
<table>
<tr>
<td>
</td>
<td>
<input name="quiz_assign_id" type="hidden" value=" <?php echo $quiz_assign_id; ?>" /> <input name="quiz_question_id" type="hidden" value=" <?php echo $row["quiz_question_id"]; ?>" /></td>
<td> </td>
</tr>
<tr>
<td>
<h4>Question <?php echo $i++; ?> </h4>
</td>
<td>
<h4><?php echo $row["question"]; ?> </h4>
</td>
<td> </td>
</tr>
<tr>
<td>
<h4>A</h4>
</td>
<td><?php echo $row["option1"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option A" style="width: 20px" /></td>
</tr>
<tr>
<td>
<h4>B</h4>
</td>
<td><?php echo $row["option2"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option B" /></td>
</tr>
<tr>
<td>
<h4>C</h4>
</td>
<td><?php echo $row["option3"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option C" /></td>
</tr>
</table>
<?php
}
?>
<input name="Submit1" type="submit" value="submit" />
</form>
</div>
Upon submission I run the following script, which captures the response but does not get the question_id and Quiz_Assign_ID and does not update the values in the database:
<?php
if(!empty($_POST['Response'])) {
foreach ($_POST['Response'] as $value) {
$quiz_assign_id=trim($_POST['quiz_assign_id']);
$quiz_question_id=$_POST['quiz_question_id'];
echo 'Answer'; echo $value;
echo 'Question:'; echo $quiz_question_id;
echo 'Student ID'; echo $quiz_assign_id; echo 'successfully assigned! <br>';
$stmt = $conn -> prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
if (
$stmt &&
$stmt -> bind_param('sss', $value, $quiz_assign_id, $quiz_question_id) &&
$stmt -> execute() &&
$stmt -> affected_rows === 1
) {
echo "<script>
alert('Responses submitted!');
window.history.go(-2);
</script>";
} else {
echo"<script>
window.history.go(-2);
</script>";
}
}
}
?>
I have been playing with it for hours, but with no luck.
Because you are using check boxes en not radio buttons, you should change your input checkbox name attribute, so it's sending a nested array with the question ID as a key and the answers array as the value, like so: (notice the extra []) Also $quiz_question_id is not defined, you should use the $row array.
<input name="Response[<?php echo $row['quiz_question_id']; ?>][]" type="checkbox" value="Option A" style="width: 20px" /></td>
Because the response array is now nested, the question answers are grouped by question_id. To iterate over the nested response array, use the following for loop:
foreach ($_POST['Response'] as $question_id => $answered) {
echo "Question ID:".$question_id."<br />";
// iterate answers
foreach ($answered as $answer) {
echo "Answered: ".$answer."<br />";
}
// Or transform to comma separated string
echo "Answered: ".implode(", ", $answered)."<br />";
}
So your LP_Quiz_Student_Quiz_Responses.php could look like this:
if(!empty($_POST['Response'])) {
$done = 0;
foreach ($_POST['Response'] as $quiz_question_id => $values) {
$quiz_assign_id = trim($_POST['quiz_assign_id']);
echo 'Answers'; print_r($values); // Values is an array here.
echo 'Question:'; echo $quiz_question_id;
echo 'Student ID'; echo $quiz_assign_id; echo 'successfully assigned! <br>';
// Because $values is an array, transform it into a comma separated string to insert them into the database
// But you could also make a database table with answers and loop over the $values array.
$value = implode(', ', $values);
$stmt = $conn->prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
$stmt->bind_param('sss', $value, $quiz_assign_id, $quiz_question_id);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$done++;
}
}
echo "<script>";
if ($done) {
echo "alert('Responses submitted!');";
}
echo "window.history.go(-2);";
echo "</script>";
}
To accommodate both type of questions with check boxes and questions with radio buttons, you can use the same response code, but first check if its an array before transforming it into a string.
Questions with radio buttons, one answer per question possible:
<input name="Response[<?php echo $row['quiz_question_id']; ?>]" type="radio" value="Option A" style="width: 20px" /></td>
Questions with check boxes, multiple answers per question possible:
<input name="Response[<?php echo $row['quiz_question_id']; ?>][]" type="checkbox" value="Option A" style="width: 20px" /></td>
And now your LP_Quiz_Student_Quiz_Responses.php could look like this:
if(!empty($_POST['Response'])) {
$done = 0;
foreach ($_POST['Response'] as $quiz_question_id => $values) {
$quiz_assign_id = trim($_POST['quiz_assign_id']);
// If it's an array (checkbox), transform to string.
// Else it is already a string (radio).
if (is_array($values)) {
$values = implode(', ', $values);
}
$stmt = $conn->prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
$stmt->bind_param('sss', $values, $quiz_assign_id, $quiz_question_id);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$done++;
}
}
echo "<script>";
if ($done) {
echo "alert('".$done." Responses submitted!');";
}
echo "window.history.go(-2);";
echo "</script>";
}
But with above code you can accommodate all kind of field types.
To put it simple:
foreach ($_POST['Response'] as $question_id => $answered) {
echo "Question ID:".$question_id."<br />";
// Check if array, it's a checkbox or multiple select question
if (is_array($answered)) {
// iterate answers
foreach ($answered as $answer) {
echo "Answered: ".$answer."<br />";
}
// Or transform to comma separated string
echo "Answered: ".implode(", ", $answered)."<br />";
} else {
// radio, hidden, input, select or textarea question
echo "Answered: ".$answered."<br />";
}
}
I hope this points you in the right direction.

Not Able to save data to Mysql database

I am developing a simple attendance system in which the attendance is taken by the a teacher and then saved to the database. However, I am having a problem with saving the data to the database. when i click on "submit attendance" the data won't be submitted to the database. i use register.php to register students but take the attendance in different file.
Below is the code i use to submit. Can someone help me? Thanks.
sorry the file i shared was supposed to save data to mysql database. Below is the file which takes the data and am still having the problem for saving it.
this is the teacher file to take the attendance
teacher.php
<?php
$pageTitle = 'Take Attendance';
include('header.php');
require("db-connect.php");
if(!(isset($_COOKIE['teacher']) && $_COOKIE['teacher']==1)){
echo 'Only teachers can create new teachers and students.';
$conn->close();
include('footer.php');
exit;
}
//get session count
$query = "SELECT * FROM attendance";
$result = $conn->query($query);
$sessionCount=0;
setcookie('sessionCount', ++$sessionCount);
if(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
$sessionCount = $row['session'];
setcookie('sessionCount', ++$sessionCount);
}
}
if(isset($_GET['class']) && !empty($_GET['class'])){
$whichClass = $_GET['class'];
$whichClassSQL = "AND class='" . $_GET['class'] . "'";
} else {
$whichClass = '';
$whichClassSQL = 'ORDER BY class';
}
echo '
<div class="row">
<div class="col-md-4">
<div class="input-group">
<input type="number" id="session" name="sessionVal" class="form-control" placeholder="Session Value i.e 1" required>
<span class="input-group-btn">
<input id="submitAttendance" type="button" class="btn btn-success" value="Submit Attendance" name="submitAttendance">
</span>
</div>
</div>
<div class="col-md-8">
<form method="get" action="' . $_SERVER['PHP_SELF'] . '" class="col-md-4">
<select name="class" id="class" class="form-control" onchange="if (this.value) window.location.href=this.value">
';
// Generate list of classes.
$query = "SELECT DISTINCT class FROM user ORDER BY class;";
$classes = $classes = mysqli_query($conn, $query);
if($classes && mysqli_num_rows($classes)){
// Get list of available classes.
echo ' <option value="">Filter: Select a class</option>';
echo ' <option value="?class=">All classes</option>';
while($class = $classes->fetch_assoc()){
echo ' <option value="?class=' . $class['class'] . '">' . $class['class'] . '</option>';
}
} else {
echo ' <option value="?class=" disabled>No classes defined.</option>';
}
echo '
</select>
</form>
</div>
</div>
';
$query = "SELECT * FROM user WHERE role='student' $whichClassSQL;";
$result = $conn->query($query);
?>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<form method="post" action="save-attendance.php" id="attendanceForm">
<?php
if(mysqli_num_rows($result) > 0){
$i=0;
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="hidden" value="<?php echo($row['id']);?>" form="attendanceForm"><input type="text" readonly="readonly" name="name[<?php echo $i; ?>]" value="<?php echo $row['fullname'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="email[<?php echo $i; ?>]" value="<?php echo $row['email'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="class[<?php echo $i; ?>]" value="<?php echo $row['class'];?>" form="attendanceForm"></td>
<td><input type="radio" value="present" name="present[<?php echo $i; ?>]" checked form="attendanceForm"></td>
<td><input type="radio" value="absent" name="present[<?php echo $i; ?>]" form="attendanceForm"></td>
</tr>
<?php $i++;
}
}
?>
</form>
</tbody>
</table>
<script>
$("#submitAttendance").click(function(){
if($("#session").val().length==0){
alert("session is required");
} else {
$.cookie("sessionVal", $("#session").val());
var data = $('form#attendanceForm').serialize();
$.ajax({
url: 'save-attendance.php',
method: 'post',
data: {formData: data},
success: function (data) {
console.log(data);
if (data != null && data.success) {
alert('Success');
} else {
alert(data.status);
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
<?php
$conn->close();
include('footer.php');
save-attendance.
<?php
//include ("nav.php");
require("db-connect.php");
$query = "SELECT * FROM user WHERE role='student'";
$result = $conn->query($query);
$nameArray = Array();
$count = mysqli_num_rows($result);
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
}
//save record to db
if(isset($_POST['formData'])) {
//increment the session count
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
setcookie('sessionCount', ++$sessionCount);
}
parse_str($_POST['formData'], $searcharray);
//print_r($searcharray);die;
//print_r($_POST);
for ($i = 0 ; $i < sizeof($searcharray) ; $i++){
// setcookie("checkloop", $i);;
$name = $searcharray['name'][$i];
$email= $searcharray['email'][$i];
$class = $searcharray['class'][$i];
$present= $searcharray['present'][$i];
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
//get class id
$class_query = "SELECT * FROM class WHERE name='".$class."'";
$class_id = mysqli_query($conn, $class_query);
if($class_id){
echo "I am here";
while($class_id1 = $class_id->fetch_assoc()){
$class_id_fin = $class_id1['id'];
echo $class_id['id'];
}
}
else{
echo "Error: " . $class_query . "<br>" . mysqli_error($conn);
}
//get student id
$student_query = "SELECT * FROM user WHERE email='".$email."'";
$student_id = $conn->query($student_query);
if($student_id) {
while ($student_id1 = $student_id->fetch_assoc()) {
$student_id_fin = $student_id1['id'];
}
}
//insert or update the record
$query = "INSERT INTO attendance VALUES ( '".$class_id_fin."', '".$student_id_fin."' , '".$present."','".$sessionVal."','comment')
ON DUPLICATE KEY UPDATE isPresent='".$present."'";
print_r($query);
if(mysqli_query($conn, $query)){
echo json_encode(array('status' => 'success', 'message' => 'Attendance added!'));
} else{
echo json_encode(array('status' => 'error', 'message' => 'Error: ' . $query . '<br>' . mysqli_error($conn)));
}
}
$conn->close();
}
You did not provide a lot of information, but I understand from the comments that the error is $sessionVal is undefined.
if $_COOKIE['sessionVal'] is not set, try:
1- print_r($_COOKIE) and check if [sessionVal] is set;
2- Try to add a fallback to:
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
else {
$sessionVal = 0;
}
or
$sessionVal = (isset($_COOKIE['sessionVal'])) ? $_COOKIE['sessionVal'] : 0;
Bottom line, there is not point to check if a variable is set and not having a fallback in case it is not set.

Full Message is not showing in mobile phone using php sms api

Well, I just bought a sms api which is created by php. They provide me this 2 lines:
http://fahimit.com/smsapi.php?
user=username&pass=pass&phone=mobile_numer&senderid=sender_name&message=my_message
\well now i'm using a html form to send sms. But after message send it's not showing full sender name and message.
For example if i use "Test Sender" as sender_name and "Test message test message" as my_message then it's only showing First word like: Test as sender_name and Test as my_message. I don't understand why it's not showing full message and sender name
PHP code:
<?php
if(isset($_POST['Submit']) && $_POST['Submit'] == "Send SMS")
{
$write_numer = $_POST['write_number'];
$sender = inputvalid($_POST['sender']);
$type = inputvalid($_POST['type']);
$select_msg = inputvalid($_POST['select_msg']);
$msg = $_POST['txt'];
$length = strlen($msg);
$err = array();
$ip = $_SERVER['REMOTE_ADDR'];
if(isset($write_numer) && isset($sender) && isset($type) && isset($select_msg) && isset($msg))
{
if(empty($write_numer) && empty($sender) && empty($type) && empty($select_msg) && empty($msg))
$err[] = "All field require";
else
{
if(empty($write_numer))
$err[] = "Write your mobile number";
elseif(strlen($write_numer) > 13 || strlen($write_numer) < 13)
$err[] = "Your mobile number format is not correct";
elseif(!is_numeric($write_numer))
$err[] = "Your mobile number format is not correct";
elseif (!preg_match("/^8801(6|5|7|8|9|1)\d{8}/", $write_numer))
$err[] = "Invalid mobile number";
if(empty($sender))
$err[] = "Select sender name";
if(empty($type))
$err[] = "Select your message type";
if(empty($select_msg) && empty($msg))
$err[] = "Select your message";
}
}
//error count
if(!empty($err))
{
echo "<div class='error'>";
foreach($err as $er)
{
echo "<font color=red>$er.</font><br/>";
}
echo "</div>";
echo "<br/>";
}
else
{
$sms = "http://fahimit.com/smsapi.php?user=MYUSERNAME&pass=MYPASS&phone=".$write_numer."&senderid=".$sender."&message=".$msg."";
$sms = file_get_contents($sms);
if($sms)
{
echo "<div class='success'>Successfully sent your message to $write_numer. Thank You.</div>";
$sql = mysql_query("INSERT INTO e_sent_sms VALUES('', '', '', '$write_numer', '$msg', '', '', '$length', '$type', '$sender', '$current_date', '$ip' )");
}
else
{
mysql_error();
}
}
}
?>
HTML CODE:
<form name="frm" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<table width="800" border="0" cellspacing="10" cellpadding="0" style="float:left; position:relative;">
<tr>
<td>Write Number</td>
<td><input type="text" name="write_number" placeholder="Write your mobile number" class="td3" value="<?php if(isset($_POST['write_number'])) echo $_POST['write_number']; ?>" /><span style="color:#033;">* Mobile number must start with 8801XXXXXXXXX</span></td>
</tr>
<tr>
<td>Sender</td>
<td><input type="text" name="sender" placeholder="Sender name" class="td3" value="<?php if(isset($_POST['sender'])) echo $_POST['sender']; ?>" /></td>
</tr>
<tr>
<td>Message type</td>
<td>
<select name="type" class="select">
<option value="">--Select--</option>
<option value="5" <?php if(isset($_POST['type']) && $_POST['type'] == "5") echo 'selected = "selected"'; ?>>Text</option>
<option value="1" <?php if(isset($_POST['type']) && $_POST['type'] == "1") echo 'selected = "selected"'; ?>>Flash</option>
<option value="3" <?php if(isset($_POST['type']) && $_POST['type'] == "3") echo 'selected = "selected"'; ?>>Arabic</option>
<option value="2" <?php if(isset($_POST['type']) && $_POST['type'] == "2") echo 'selected = "selected"'; ?>>Unicode</option>
<option value="6" <?php if(isset($_POST['type']) && $_POST['type'] == "6") echo 'selected = "selected"'; ?>>Unicode Flash</option>
<option value="4" <?php if(isset($_POST['type']) && $_POST['type'] == "4") echo 'selected = "selected"'; ?>>Wap Push</option>
</select>
</td>
</tr>
<tr>
<td>Select message</td>
<td>
<select name="select_msg" class="select" id="carDealer">
<option value="">--Select Message--</option>
<?php
$sql = mysql_query("SELECT DISTINCT msg FROM e_sms_draft");
while($res = mysql_fetch_array($sql))
{
$draft = inputvalid($res['msg']);
$draft = stripslashes($draft);
if(isset($_POST['select_msg']) && $_POST['select_msg'] == "$draft")
$sel = 'selected = "selecteds"';
else
$sel = "";
echo "<option value='$draft' $sel>$draft</option>";
}
?>
</select>
</td>
</tr>
<td valign="top">Message</td>
<td><textarea class="textarea2" id="carPark" placeholder="Your message" name="txt" onkeyup="counter(this);"><?php if(isset($_POST['txt'])) echo $_POST['txt']; ?></textarea>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function putIt(e) {
$("#carPark").val(e.target.value);
}
$("#carDealer").on("change", putIt);
</script>
<br/><input type="" name="lbl" style="border:none;"><br/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Save SMS" class="view"/>
<input type="submit" name="Submit" value="Send SMS" class="submit"/></td>
</tr>
</table>
</form>
Can you tell me what's wrong in my code ?
You need to urlencode your text before passing it to the URL. Do like this
$sender = urlencode($sender);
$msg = urlencode($msg);
$sms = "http://fahimit.com/smsapi.php?user=MYUSERNAME&pass=MYPASS&phone=".$write_numer."&senderid=".$sender."&message=".$msg."";
Do this for all the variables that you are going to send it to the URL.

Editing Checkboxes, radios, and dropdowns

I found this site providing code for creating, reading, updating and deleting. I am confused about how to add checkboxes, radio buttons, and dropdowns
http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/
I'm not concerned with the pagination at all——my primary concern is to be able to put in two dropdowns, yes/no radio button, and a collection of 3 checkboxes using PHP.
My attempts were useless as when I tried to edit choices the values did not stay. Included are my three files: pets, editpets, and view.(I changed the file name for database, etc.)
<?php
function renderForm($first, $last, $pets, $size, $type, $years, $error)
{
?>
<!DOCTYPE html>
<html>
<head>
<title>New Customer</title>
</head>
<body>
<?php
// display possible errors
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>First Name:</strong> <input type="text" name="firstname" value="<?php echo
$first; ?>" />
<strong>Last Name:</strong> <input align="center" type="text" name="lastname" value="<
?php echo $last; ?>" /><br/>
<p><strong>No. Pets </strong>
<select name="pets">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</p>
<br/>
<strong>Size? </strong>
<br/>
Big<input type="radio" value="Yes" name="size" checked><?php echo $size; ?><br />
Small<input type="radio" value="No" name="size"<?php echo $size; ?><br />
<br />
<p><strong>Type</strong><br/>
<input name="type[]" type="checkbox" id="type[]"/>
Cats
<input name="type[]" type="checkbox" id="type[]"/>
Dogs
<input name="type[]" type="checkbox" id="type[]"/>
Others
</p>
<br/>
<strong>Years? </strong>
<select name="year">
<option value="Five or Less">Five or More</option>
<option value="Six or More">Six or More</option>
</select><br/>
<input style="color:purple;" type="submit" name="submit" value="Create My Order :-)">
</div>
</form>
<center>Click Here for Orders</center>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if my form submits and, upon triumph, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, check its validity
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$pets = $_POST['pets'];
$size = mysql_real_escape_string(htmlspecialchars($_POST['size']));
$type = serialize(mysql_real_escape_string(implode(',', $_POST['type'])));
$years = mysql_real_escape_string(htmlspecialchars($_POST['years']));
// check to make sure everything is filled!
if ($firstname == '' || $lastname == '' || $pets == '' || $size == '' || $type == '' || $years == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, show the form again
renderForm($firstname, $lastname, $pets, $size, $type, $years, $error);
}
else
{
// save the data to the database
mysql_query("INSERT customers SET firstname='$firstname', lastname='$lastname', pets='$pets', size='$size', type='$type', years='$years'")
or die(mysql_error());
// once saved, redirect to cheview page
header("Location: view.php");
}
}
else
// if the form is not submitted, show my form again.
{
renderForm('','','','','','','');
}
?>
<?php
$types = array("Cats", "Dogs", "Others");
function renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>First Name: </strong> <input type="text" name="firstname" value="<?php echo $firstname; ?>" /><br/>
<strong>Last Name: </strong> <input type="text" name="lastname" value="<?php echo $lastname; ?>" /><br/>
<p><strong>No. Pets </strong>
<select name="pets">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</p>
<strong>Size? </strong>
<br/>
Big<input type="radio" value="Yes" name="size" checked><?php echo $size; ?><br />
Small<input type="radio" value="No" name="size"<?php echo $size; ?><br />
<br />
<br />
<br />
<p><strong>Type</strong><br/>
<input name="type[]" type="checkbox" id="type[]"/>
Cats
<input name="type[]" type="checkbox" id="type[]"/>
Dogs
<input name="type[]" type="checkbox" id="type[]"/>
Others
</p>
<br/>
<strong>Years? </strong>
<select name="year">
<option value="Five or Less">Five or More</option>
<option value="Six or More">Six or More</option>
</select><br/>
<br /><br />
<input type="submit" name="submit" value="Resubmit My Order :-)">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// check for id being an integer
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$pets = $_POST['pets'];
$size = mysql_real_escape_string(htmlspecialchars($_POST['size']));
$type = serialize(mysql_real_escape_string(implode(',', $_POST['type'])));
$years = mysql_real_escape_string(htmlspecialchars($_POST['years']));
// check that firstname/lastname fields are both filled in
if ($firstname == '' || $lastname == '' || $pets == '' || $size == '' || $type == '' || $years == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE customers SET firstname='$firstname', lastname='$lastname', pets='$pets', size='$size', type='$type', years='$years' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM customers WHERE id='$id' ")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$pets = $row['pets'];
$size = $row['size'];
$type = serialize($row['type']);
$years = $row['years'];
// show form
renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View customer orders</title>
</head>
<body>
<?php
include('connect-db.php');
$result = mysql_query("SELECT * FROM customers")
or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Pets</th>
<th>Size</th>
<th>Type</th>
<th>Years</th>
<th></th>
<th></th>
</tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
echo '<td>' . $row['pets'] . '</td>';
echo '<td>' . $row['size'] . '</td>';
echo '<td>' . $row['type']. '</td>';
echo '<td>' . $row['years'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
I'm honestly lost at this point. I've been working on this for an entire month and I have no idea what I'm doing any more. I'd be so thankful if anyone can help me to edit this to work.
Thanks everyone.
Right, to get your saved results from the database I'm sure you're aware of how to do this.
For your radio buttons you're going to want to select your 'size' value from the database and use an if statement to determine which radio button will be 'checked'
forename/surname is a matter of simply getting the forename/surname from database and setting the appropriate input tags to the acquired values
You've already posted a technique for handling the combo/drop-down boxes
you'd perform a similar process for the 'type' checkboxes, compare your database values to the values of your checkbox input tags and if the value matches, set the checkbox to checked.
Next time please be more specific in what you are asking for help with and separate your code into segments that correspond with the files it is contained in.
if you have 3 files, have a code block for each file.

form submit not working

I have a table that prints out all available cameras. It uses a form to change these settings. The problem is that the form only updates the last camera in the entry. In other words if I change the form and hit "Apply" for the last camera in the list it will work. If I change the form for any other camera in this list it changes the one to have the same settings as the last camera in the list. There are no issues with any values as far as I can tell.
Sorry for the long dump here, but without being able to narrow down the problem I thought I should include the bulk of it:
// Dont allow direct linking
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
//get current user
$user =& JFactory::getUser();
// get a reference to the database
$db = &JFactory::getDBO();
$query_camera_name = "SELECT camera_id, camera_name, camera_status, camera_quality, camera_hash, camera_type FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
if (isset($_POST['apply_changes'])) {
//process changes to camera options
$camera_id = $_POST['camera_id'];
$camera_status = check_input($_POST['camera_status']);
$camera_name = check_input($_POST['camera_name'], "You entered an empty camera name. Enter another name and apply changes.");
$camera_quality = check_input($_POST['camera_quality']);
$query_insert_camera = 'UPDATE `#__cameras` SET `camera_status` ="'.$camera_status.'", `camera_name` ="'.$camera_name.'", `camera_quality` ="'.$camera_quality.'" WHERE `camera_id`='.$camera_id;
$db->setQuery($query_insert_camera);
$db->query();
header("location: " . $_SERVER['REQUEST_URI']);
}
echo "<html>";
echo "<head>";
<link href="dashboard/webcam_widget.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function oncameraSubmit(camera_id)
{
document.active_cameras.camera_id.value = camera_id;
return confirm('Apply changes?');
}
</script>
<?php
echo "</head>";
echo "<body>";
if (!isset($result_cameras))
{
//TODO
}
else
{
if ($num_rows == 0)
{
echo '<b><i><center>You currently have no cameras setup. Add a Camera below.</center></i></b>';
}
else
{
?>
<form name="active_cameras" action="<?php htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<input type="hidden" name="camera_id" value="" />
<table id="webcam-table">
<thead>
<tr>
<th>Camera Type</th>
<th>Name</th>
<th>Quality</th>
<th>Status</th>
<th>Camera Actions</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$num_rows;$i++)
{
//camera_status
if ($result_cameras[$i]["camera_status"] == "ENABLED")
{
$enabled_option = "value='ENABLED' selected='selected'";
$disabled_option = "value='DISABLED'";
}
else
{
$enabled_option = "value='ENABLED'";
$disabled_option = "value='DISABLED' selected='selected'";
}
//camera_quality
if ($result_cameras[$i]["camera_quality"] == "HIGH")
{
$high_option = "value='HIGH' selected='selected'";
$medium_option = "value='MEDIUM'";
$mobile_option = "value='MOBILE'";
}
else if ($result_cameras[$i]["camera_quality"] == "MEDIUM")
{
$high_option = "value='HIGH'";
$medium_option = "value='MEDIUM' selected='selected'";
$mobile_option = "value='MOBILE'";
}
else if ($result_cameras[$i]["camera_quality"] == "MOBILE")
{
$high_option = "value='HIGH'";
$medium_option = "value='MEDIUM'";
$mobile_option = "value='MOBILE' selected='selected'";
}
else
{
//TODO proper logging
}
//camera_type
if ($result_cameras[$i]["camera_type"] == "WEBCAM")
{
$webcam = "value='WEBCAM' selected='selected'";
$axis = "value='AXIS'";
$other = "value='IPCAM'";
}
else if ($result_cameras[$i]["camera_type"] == "AXIS")
{
$webcam = "value='WEBCAM'";
$axis = "value='AXIS' selected='selected'";
$other = "value='IPCAM'";
}
else if ($result_cameras[$i]["camera_type"] == "IPCAM")
{
$webcam = "value='WEBCAM'";
$axis = "value='AXIS'";
$other = "value='IPCAM' selected='selected'";
}
else
{
//TODO
}
?>
<tr>
<td>
<select name="camera_type">
<option <?php echo $webcam; ?>>Webcam</option>
<option <?php echo $axis; ?>>AXIS</option>
<option <?php echo $other; ?>>Other</option>
</select>
</td>
<td>
<input type="text" size="32" maxlength="64" name="camera_name" value="<?php echo $result_cameras[$i]["camera_name"]; ?>" />
</td>
<td>
<select name="camera_quality">
<option <?php echo $high_option; ?>>High</option>
<option <?php echo $medium_option; ?>>Medium</option>
<option <?php echo $mobile_option; ?>>Mobile</option>
</select>
</td>
<td>
<select name="camera_status">
<option <?php echo $enabled_option; ?>>Enabled</option>
<option <?php echo $disabled_option; ?>>Disabled</option>
</select>
</td>
<td>
<input type="submit" name="apply_changes" value="Apply" onClick="javascript:return oncameraSubmit(<?php echo $result_cameras[$i]["camera_id"]; ?>);"/>
</td>
</tr>
<?php
}
echo "</tbody>";
echo "</table>";
echo "</form>";
}
}
It looks like you have multiple HTML elements with the same name. As such, you want to get back an array of values when the form is posted.
As such, Get $_POST from multiple checkboxes looks like it might be helpful.
Alternatively, extend oncameraSubmit so that it stores all the data in a hidden input field (not just the id). Then when you update the database, use these hidden fields.
Your form element names are clashing. When you define a form element e.g. 'camera_status' twice, you will only receive the last value in the POST.
Use form array notation, e.g.: "camera_status[]" or even better "camera_status[$id]". Then your PHP code will recieve arrays as POST data and you will be able to update everything at once.

Categories