INSERT a row per array object - php

I am in the process of creating a document association tool whereby users can associate documents to a ticket from a pre-existing list of documents.
Thanks to the help of Alberto Ponte I was able to construct the initial radio box system (originally checkbox, changed for obvious reasons) from this question: Separate out array based on array data
Now that I have the radio buttons presenting correctly I am trying to get the data inserted into a MySQL with a row for each document. Following on from this I want to have it look up the table for each object and see if there is an existing entry and update that rather than inset a duplicate entry.
Apologies in advance for the soon to be depreciated code and I will be correcting the code going forward, however that is a much bigger task than I currently have time for.
Also apologies if the code is considered messy. I'm not fantastic at PHP and not too hot on best practices. Any quick pointers are always welcome.
Display code:
<?php
include "../includes/auth.php";
include "../includes/header.php";
## Security ########################################################
if ($company_id != 1 OR $gid < 7) {
echo' <div class="pageheader">
<div class="holder">
<br /><h1>Access Denied <small> Your attempt has been logged</small></h1>
</div>
</div>
';
exit();
}
// GET Values ###################################################
$jat_id = intval($_GET['id']);
$div_id = intval($_GET['div_id']);
## Page Start ########################################################
echo '
<div class="pageheader">
<div class="holder">
<br /><h1>Clovemead Job Management Platform<small> Welcome...</small></h1>
</div>
</div>
<div class="well5" style="width:1000px !important;">
<h3>Create Document Association</h3>
<table border=1>
<tr>
<td align=center><p>Here you can associate documents to Jobs and Tasks to.</p> </td>
</tr>
</table>';
$order2 = "SELECT * FROM documents";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
}
echo '
<h3>Documents</h3>
<table border=1>
<tr><th>Document Name</th><th>Document Type</th><th>Required</th><th>Optional</th><th>Not Required</th></tr>
';
$order2 = "SELECT * FROM documents ORDER BY type_id";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
$doc_type_id = $row2['type_id'];
echo '
<tr>
<td>'.$nice_name.'</td>';
$order3 = "SELECT * FROM document_types WHERE id = '$doc_type_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type_name = $row3['type_name'];
echo '
<td>'.$type_name.'</td>
<form method="post" action="create-doc-assoc-exec.php">
<input type="hidden" value="'.$doc_id.'" name="doc_id">
<input type="hidden" value="'.$jat_id.'" name="jat_id">
<input type="hidden" value="'.$div_id.'" name="div_id">';
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result400 = mysql_query($order4);
$_results = mysql_fetch_array($result400);
if (!$_results) {
echo '
<td><input type="radio" name="req0" value="2"></td>
<td><input type="radio" name="req0" value="1"></td>
<td><input type="radio" name="req0" value="0" checked ></td>';
} else {
foreach ($_results as $result400) {
$requirement = $_results['requirement'];
}
$name = "req".$doc_id;
echo '
<input type="hidden" value ="'.$name.'" name="name">
<td><input type="radio" name="'.$name.'" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
echo '
</tr>';
}
echo '
</table>
<input type="submit" name="submit value" value="Create Document Association" class="btn success Large"></form>';
$order2 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$dbname = $row2['division_dbname'];
$order3 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type = $row3['type'];
$type2 = strtolower($type);
echo '
<input type="button" value="Back" onclick="window.location='./view-'.$type2.'.php?id='.$jat_id.''" class="btn primary Large">
';
}}
echo '
</div>';
include "../includes/footer.php";
?>
Execute Code:
<?php
include "../includes/dbconnect.php";
$name = $_POST['name'];
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$doc_id = intval($_POST['doc_id']);
$jat_id = intval($_POST['jat_id']);
$div_id = intval($_POST['div_id']);
$req = intval($_POST[$name]);
$req_blank = intval($_POST['req0']);
if ($req_blank == 0) {
$requirement = 0;
} elseif ($req_blank == 1) {
$requirement = 1;
} elseif ($req_blank == 2) {
$requirement = 2;
} elseif ($req == 0) {
$requirement = 0;
} elseif ($req == 1) {
$requirement = 1;
} elseif ($req == 2) {
$requirement = 2;
}
foreach ($doc_id as $doc_id2) {
$order = "INSERT INTO document_assoc (jat_id, dept_id, doc_id, requirement) VALUES ('$jat_id', '$div_id', '$doc_id2', '$requirement')";
$result = mysql_query($order);
$order1 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result1 = mysql_query($order1);
while ($row1 = mysql_fetch_array($result1)) {
$dbname = $row1['division_dbname'];
$order2 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$type = $row2['type'];
$type2 = strtolower($type);
if($result){
header("location:view-$type2.php?id=$jat_id&creation=success");
} else {
header("location:view-$type2.php?id=$jat_id&creation=failed");
}
}}
}
?>
A few reference points:
$doc_id is the ID of each document which is to be passed over as an array for use in a (i believe) foreach insert
$jat_id is the ticket id documents are being associated to
$div_id is the department the ticket is associated
And the radio boxes are to decider the requirement of each document. To be passed over inline with $doc_id
What I have tried:
After a fair bit of searching - finding nothing - rechecking my terminology and searching again I managed to find the suggestion of using base64_encode(serialize()) on the arrays but I could not get this to work.

Related

Update multiple record with single query in database using php [duplicate]

This question already has an answer here:
Post form and update multiple rows with mysql
(1 answer)
Closed last year.
I am making an invoice in PHP where multiple products are inserted at once into one table and there grand total goes to another table. I am trying to UPDATE the invoice in MYSQL and PHP. When I press the submit button, the multiple records data from the form goes to the update.php but the query does not run.
database.php
<?php
$connect = mysqli_connect('localhost','root','','invoice');
if (!$connect){
die("Connection failed: " . mysqli_connect_error());
}
?>
edit_invoice.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
table,tr,td,th { border: 1px black solid;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Back to Invoice List<br><br>
<?php
include('database.php');
$invoice_number = $_GET['invoice_number'];
$sql = "SELECT * from invoice where invoice_number = '$invoice_number' ";
$query = mysqli_query($connect, $sql);
if ($query->num_rows > 0) {
// output data of each row
$fetch = $query->fetch_assoc();
}
?>
<form method="POST" action="update_invoice.php">
<table>
<thead>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Width</th>
<th>Height</th>
<th>Total</th>
<th>Action</th>
</thead>
<?php
$sql2 = "SELECT * from invoice_order where invoice_number = '$invoice_number' ";
$query2 = mysqli_query($connect, $sql2);
if ($query2->num_rows > 0) {
// output data of each row
$srno = 1;
$count = $query2->num_rows;
for ($i=0; $i < $count; $i++) {
while($row = $query2->fetch_assoc()) {
?>
<tbody id="product_table">
<tr>
<td><input type="text" name="product[]" value="<?php echo $row["product"]; ?>"></td>
<td><input type="text" name="price[]" value="<?php echo $row["price"]; ?>"></td>
<td><input type="text" name="quantity[]" value="<?php echo $row["quantity"]; ?>"></td>
<td><input type="text" name="width[]" value="<?php echo $row["width"]; ?>"></td>
<td><input type="text" name="height[]" value="<?php echo $row["height"]; ?>"></td>
<td><input type="text" name="total[]" value="<?php echo $row["total"]; ?>" class="totalPrice" readonly></td>
<td><input type="button" value="X" onclick="deleteRow(this)"/></td>
</tr>
</tbody>
<?php
}
}
} else {
echo "No Record Found";
}
?>
<input type="button" name="submit" value="Add Row" onclick="add_fields();">
<span>Invoice Date:<input type="date" value="<?php echo $fetch["invoice_date"]; ?>" name="invoice_date"></span>
<span>Invoice #:<input type="text" name="invoice_number" value="<?php echo $fetch["invoice_number"]; ?>" readonly></span>
<span>Select Customer:
<select name="to_user" class="form-control">
<option><?php echo $fetch["customer_id"]; ?></option>
<?php
include('database.php');
$sql = mysqli_query($connect, "SELECT * From customer");
$row = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
echo "<option value='". $row['customer_id'] ."'>" .$row['customer_id'] ." - " .$row['customer_name'] ."</option>" ;
}
?>
</select>
</span>
</table>
<span>Grand Total<input type="text" name="grandtotal" id="grandtotal" value="<?php echo $fetch["grandtotal"]; ?>" readonly></span><br><br>
<span>Paid Amount<input type="text" name="paid" id="paid" value="<?php echo $fetch["paid"]; ?>"></span><br><br>
<span>Balance<input type="text" name="balance" id="balance" value="<?php echo $fetch["balance"]; ?>" readonly></span><br><br>
<input type="submit" name="send" value="Submit">
</form>
</body>
<script>
const table = document.getElementById('product_table');
table.addEventListener('input', ({ target }) => {
const tr = target.closest('tr');
const [product, price, quantity, width, height, total] = tr.querySelectorAll('input');
var size = width.value * height.value;
var rate = price.value * quantity.value;
if (size != "") {
total.value = size * rate;
}else{
total.value = rate;
}
totalPrice();
});
function add_fields() {
var row = document.createElement("tr");
row.innerHTML =
'<td><input type="text" name="product[]"></td>' +
'<td><input type="text" name="price[]"></td>' +
'<td><input type="text" name="quantity[]"></td>' +
'<td><input type="text" name="width[]" value="0"></td>' +
'<td><input type="text" name="height[]" value="0"></td>' +
'<td><input type="text" name="total[]" class="totalPrice" readonly></td>' +
'<td><input type="button" value="X" onclick="deleteRow(this)"/></td>';
table.appendChild(row);
}
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
totalPrice();
}
function totalPrice() {
var grandtotal = 0;
var paid = 0;
$(".totalPrice").each(function() {
grandtotal += parseFloat($(this).val());
paid = grandtotal;
});
$("#grandtotal").val(grandtotal);
$("#paid").val(paid);
}
$(document).ready(function() {
$('#paid').on('input', function() {
grandtotal = $("#grandtotal").val();
paid = $("#paid").val();
balance = parseFloat(grandtotal) - parseFloat(paid);
$("#balance").val(balance);
})
});
</script>
</html>
Update_invoice.php
<?php
include('database.php');
if (isset($_POST['send'])) {
$product = $_POST['product'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$width = $_POST['width'];
$height = $_POST['height'];
$total = $_POST['total'];
$customer_id = $_POST['to_user'];
$invoice_date = $_POST['invoice_date'];
$invoice_number = $_POST['invoice_number'];
$grandtotal = $_POST['grandtotal'];
$paid = $_POST['paid'];
$balance = $_POST['balance'];
$amount_status = "";
if ($grandtotal == $paid) {
$amount_status = "Paid";
} elseif ($grandtotal == $balance) {
$amount_status = "Due";
} else {
$amount_status = "Partial";
}
// Start of Updating data to invoice_order table
for ($i = 0; $i < count($_POST['total']); $i++) {
if ($i <> count($_POST['total'])) {
$sql = "UPDATE invoice_order SET invoice_number = '$invoice_number' , product = '$_POST['product'][$i]', price = '$_POST['price'][$i]' , quantity = '$_POST['quantity'][$i]', width = '$_POST['width'][$i]' , height = '$_POST['height'][$i]' , total = '$_POST['total'][$i]' WHERE invoice_number='$invoice_number' ";
$query = mysqli_query($connect, $sql);
if ($query) {
header('location: list_invoice.php');
} else {
echo "Unable to enter records in invoice_order table";
}
}
}
// End of updating data to invoice_order table
// Start of updating data to invoice table
$sql2 = "UPDATE invoice SET customer_id = '$customer_id', grandtotal = '$grandtotal', invoice_number = '$invoice_number', invoice_date = '$invoice_date', paid = '$paid', balance = '$balance', amount_status = '$amount_status' WHERE invoice_number='$invoice_number' ";
$query2 = mysqli_query($connect, $sql2);
if ($query2) {
header('location: list_invoice.php');
} else {
echo "Unable to enter record in invoice table";
}
// End of updating data to invoice table
}
?>
The approach you are using is not the preferred way of doing the job. Use mysql prepare statement. This will make the code clean, easy to read and secured. Here is the link you can refer Mysql Prepared Statement in PHP

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.

Show images from database in Php/Mysql

I try to make online quiz with images questions, and i need your help/advice.
My images is stored on database where have an id "image". My upload works fine, image is stored on database...but i can't show image in questions.
Here is my structure from database: http://imageshack.com/a/img923/8746/Kf16xl.jpg
And that's my code from show questions with image:
<?php
session_start();
require_once("scripts/connect_db.php");
$arrCount = "";
if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$output = "";
$answers = "";
$q = "";
$sql = mysqli_query($connection, "SELECT id FROM questions");
$numQuestions = mysqli_num_rows($sql);
if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
$currQuestion = "1";
}else{
$arrCount = count($_SESSION['answer_array']);
}
if($arrCount > $numQuestions){
unset($_SESSION['answer_array']);
header("location: index.php");
exit();
}
if($arrCount >= $numQuestions){
echo 'finished|<p>There are no more questions. Please enter your first and last name and click next</p>
<form action="userAnswers.php" method="post">
<input type="hidden" name="complete" value="true">
<input type="text" name="username">
<input type="submit" value="Finish">
</form>';
exit();
}
if (!empty($image)) {
$sqlimage = mysqli_query($connection, "SELECT * FROM questions where 'image' = $image");
$imageresult = mysqli_query($connection, $sqlimage);
while($row=mysqli_fetch_assoc($imageresult))
{
echo '<img height="300" width="300" src="data:image;base64,'.$row[2].' "> ';
}
}
$singleSQL = mysqli_query($connection, "SELECT * FROM questions WHERE id='$question' LIMIT 1");
while($row = mysqli_fetch_array($singleSQL)){
$id = $row['id'];
$thisQuestion = $row['question'];
$type = $row['type'];
$question_id = $row['question_id'];
$q = '<h2>'.$thisQuestion.'</h2>';
$sql2 = mysqli_query($connection, "SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
while($row2 = mysqli_fetch_array($sql2)){
$answer = $row2['answer'];
$correct = $row2['correct'];
$answers .= '<label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label>
<input type="hidden" id="qid" value="'.$id.'" name="qid"><br /><br />
';
}
$output = ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()">Submit</button></span>';
echo $output;
}
}
?>
The part with show images is:
if (!empty($image)) {
$sqlimage = mysqli_query($connection, "SELECT * FROM questions where 'image' = $image");
$imageresult = mysqli_query($connection, $sqlimage);
while($row=mysqli_fetch_assoc($imageresult))
{
echo '<img height="300" width="300" src="data:image;base64,'.$row[2].' "> ';
}
}
Thank you very much for allocating your time!

Using combobox on a edit page with PHP

I have two tables, tblPlayer(PlayerID, PlayerName,PlayerTeam(int) ) and tblTeams (TeamID, TeamName)
On a PHP page I have a function to find the selected player, function is as follows,
function find_selected_player() {
global $sel_player;
if (isset($_GET['id'])) {
$sel_player = get_player_by_id($_GET['id']);
} else {
$sel_player = NULL;
}
}
my other function as follows,
function get_player_by_id($player_id) {
global $conn;
$query = "SELECT * ";
$query .= "FROM tblPlayer ";
$query .= "WHERE PlayerID =" . $player_id ." ";
$query .= "LIMIT 1";
$result_set = mysql_query($query, $conn);
confirm_query($result_set);
if ($player = mysql_fetch_array($result_set)) {
return $player;
} else {
return NULL;
}
}
So on the form to edit I can get all values like
<input type="text" name="PlayerName" value="<?php echo $sel_player['PlayerName']; ?>" />
But...:) when I try to fill up a combo box with the reverse way I am stuck there. When adding something this works like a charm but $sel_player['PlayerTeam'] is giving me only ID :(
<?php include "conn.php" ?>
<?php include "function.php" ?>
<?php find_selected_player() ?>
<h2>Edit: <?php echo $sel_player['PlayerName'] ." ". $sel_player['PlayerLname']; ?></h2>
<form action="player.php" method="post">
<table>
<tr>
<td>Name: </td>
<td><input type="text" name="PlayerName" value="<?php echo $sel_player['PlayerName']; ?>" /></td>
</tr>
<tr>
<td>Lastname:</td>
<td><input type="text" name="PlayerLname" value="<?php echo $sel_player['PlayerLname']; ?>" /></td>
</tr>
<tr>
<td>Team:</td>
<td>
<?php
$sql = "SELECT TeamName, TeamID FROM tblTeam";
$result = mysql_query($sql);
echo '<select name="TeamName"><option>';
echo "Choose a team.</option>";
echo '<option selected>' . $sel_player['PlayerTeam'] . '</option>';
while ($row = mysql_fetch_array($result)) {
$team_name= $row["TeamName"];
$team_id = $row["TeamID"];
echo "<option value=\"$team_id\">$team_name</option>";
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Save" /></td>
<td align="right"> </td>
</tr>
</table>
</form>
<?php ob_end_flush() ?>
<?php include ("footer.php") ?>
You should update your code to use MySQLi_*, or PDO. I've gotten you started here. Try this out and see how it works for you.
function getPlayerByID($pid = '')
{
global $conn;
if($pid == '')
return false;
$sql = mysql_query("SELECT * FROM tblPlayer WHERE PlayerID = '$pid'", $conn);
$row = mysql_fetch_array($sql);
if(mysql_num_rows($sql) == 1)
return $row;
else
return false;
}
$id = isset($_GET['id']) ? $_GET['id'] : '';
$sel_player = getPlayerByID($id);
$sql = mysql_query("SELECT TeamName, TeamID FROM tblTeam");
$select = '<select name=""><option>Choose a Team</option>';
while($row = mysql_fetch_array($sql))
{
$team_id = $row['TeamID'];
$team_name = $row['TeamName'];
$selected = $team_id == $sel_player['PlayerTeam'] ? 'selected' : '';
$select .= '<option ' . $selected . ' value="' . $team_id . '">' . $team_name . '</option>';
}
$select .= '</select>';
echo $select;
$team_adi should be $team_name
Change:
echo "<option value=\"$team_id\">$team_adi</option>";
to:
echo "<option value=\"$team_id\">$team_name</option>";
<?php
$sql = "SELECT TeamName, TeamID FROM tblTeam";
$result = mysql_query($sql);
$player_id = $_GET['id'];
$current_team = mysql_query("SELECT
tblteam.TeamID,
tblteam.TeamName,
tblplayer.PlayerID,
tblplayer.PlayerTeam,
tblplayer.PlayerName
FROM
tblplayer
INNER JOIN tblteam ON tblplayer.PlayerTeam = tblteam.TeamID
WHERE PlayerID = $player_id LIMIT 1 ");
$my_row = mysql_fetch_array($current_team);
?>
<select name="TeamName">
<option selected value="<?php echo $my_row['TeamID']; ?>"> <?php echo $my_row['TeamName']; ?> </option>
<?php
while ($row = mysql_fetch_array($result)) {
$team_name= $row["TeamName"];
$team_id = $row["TeamID"];
echo "<option value=\"$team_id\">$team_name</option>";
}
echo "</select>";
?>

Separate out array based on array data

I want to create a table for documents and allow users to select whether the document is required or not in relation to a task. I need it to check the current status of the document to see if it is already required and if it is mark the tick box as checked. There are currently 4 documents in the database and only 2 associations to 2 of the documents for this particular task.
When there is no association of a document to a task there will be no entry in the database to say that it is not associated it just simple will not be in that table.
The code I have currently will show checkboxes against those 2 documents which have associations however do not show any tick boxes at all for the ones that have no association. I would like it to still show the 3 check boxes, so that the user can change its association, but as default it should check not required. Currently It just shows no tick boxes at all. Below is the PHP snip. Please advise if you would like a screenshot or the DB dumps.
Any help would be greatly appreciated. I'm hoping its just been a long day and I am forgetting something simple.
<table border=1>
<tr>
<td align=center><p>Here you can associate documents to Jobs and Tasks to.</p> </td>
</tr>
</table>';
$order2 = "SELECT * FROM documents";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
}
echo '
<h3>Documents</h3>
<table border=1>
<tr><th>Document Name</th><th>Document Type</th><th>Required</th><th>Optional</th><th>Not Required</th></tr>
';
$order2 = "SELECT * FROM documents ORDER BY type_id";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
$doc_type_id = $row2['type_id'];
echo '
<tr>
<td>'.$nice_name.'</td>';
$order3 = "SELECT * FROM document_types WHERE id = '$doc_type_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type_name = $row3['type_name'];
echo '
<td>'.$type_name.'</td>';
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result4 = mysql_query($order4);
while ($row4 = mysql_fetch_array($result4)) {
$requirement = $row4['requirement'];
echo '
<td><input type="checkbox" name="req" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="checkbox" name="opt" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="checkbox" name="not" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
echo '
</tr>';
}
echo '
</table>';
So far I have just tried tweaking the requirement = with the final tick box. But as it is staying the same whether i use NULL ect - im guessing im missing something.
Kind Regards,
n00bstacker
You can use the following if statement to identify the situation and respond appropriately:
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result4 = mysql_query($order4);
$_results = mysql_fetch_array($result4);
if (!$_results) {
<<<< OUTPUT THE CHECKBOXES/INPUTS YOU NEED >>>>
} else {
foreach ($_results as $result) {
$requirement = $result['requirement'];
echo '
<td><input type="checkbox" name="req" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="checkbox" name="opt" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="checkbox" name="not" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
Hope this helps!

Categories