php checkbox checked on edit page - php

I have 3 tables:
people:
------------------------
peopleID,
firstname
peopletype:
------------------------
peopletypeID,
type
peoplepeopletype (junction table):
------------------------
peopleID,
peopletypeID
On the add form everything is fine, but I have problem to display checkboxes checked for the assigned peopletype
Here is my code.
Retrieve data from peoplepeopletype table :
/*PEOPLE TYPE ************* */
$stmt = $conn->prepare("SELECT * FROM peoplepeopletype WHERE peopleID=?");
// set parameters and execute
if ( !$stmt ) { echo "error"; }
else if ( !$stmt->bind_param('i', $_GET['peopleID']) ) { echo "error";}
else if ( !$stmt->execute() ) { echo "error"; }
else {
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$peopletypeIDfromdb = $row ['peopletypeID'];
echo $peopletypeIDfromdb; /*echo only for test purposes, but I don't know how to use this in the form */
}
} /* end else */
Display checkboxes :
<?php /*retrieve peopletype from db */
$sql = "SELECT * from peopletype";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo '<input required="required" type="checkbox" name="peopletypeID[]" value="' . $row["peopletypeID"] . '"';
if ($peopletypeIDfromdb = $row["peopletypeID"]) { /*problem is probably here*/
echo 'checked';
}
echo '>' . $row["type"];
}
?>
Thanks for your help!

If you can have multiple types attached to 1 person, you'll need to change the first loop to store all of them in an array. I store them as keys to have the minimum complexity of checking the existence of certain type in the future among the types assigned to the person.
$result = $stmt->get_result();
$types = array();
while($row = $result->fetch_assoc()) {
$types[$row ['peopletypeID']] = 1;
}
And then use it inside the second loop:
while($row = $result->fetch_assoc()) {
echo '<input required="required" type="checkbox" name="peopletypeID[]" value="' .
$row["peopletypeID"] . '" ';
if(isset($types[$row["peopletypeID"]]))
{
echo 'checked';
}
echo '>' . $row["type"];
}

Related

php only returning 1 row from database

I have the following php code (in a file returndata.php) to retrieve messages for a user:
$sql = 'SELECT * FROM usertimes WHERE receiver ="'. $messagesforaccount. '"';
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response['message'] = $row["message"];
$response['date'] = $row["date"];
$response['sender'] = $row["sender"];
$response['receiver'] = $row["receiver"];
}
echo json_encode($response);
} else {
echo " 0 results";
}
Then the javascript is as follows (displays the message and some information on it such as the sender, date etc. on the webpage):
$.post(
"returndata.php",
{ messagesforaccount: userAccount },
function(response) {
var sender = response.sender;
var receiver = response.receiver;
var message = response.message;
var date = response.date;
console.log('Retreived data: ', sender, receiver, message, date);
p = document.createElement('p')
p.innerHTML = message + '<br>' + 'sent by ' + sender + ' at ' + date
listmessages.appendChild(p)
}, 'json'
);
This only adds one message to the page (the last one in the database). What should the php be so it loops through all results, and for each result it adds the message to the webpage?
You did a little bit mistake there. If you want associative array for multiple data then you should have a two dimensional array and you must have an index for second dimensional array as well
<?php
$sql = 'SELECT * FROM usertimes WHERE receiver ="'. $messagesforaccount. '"';
$result = $conn->query($sql);
$response = array();
$index = 0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[$index]['message'] = $row["message"];
$response[$index]['date'] = $row["date"];
$response[$index]['sender'] = $row["sender"];
$response[$index]['receiver'] = $row["receiver"];
$index++;//incrementing index variable
}
echo json_encode($response);
} else {
echo " 0 results";
}
?>
In return you can iterate that array in this way
for ($i=0;$i<count($response);$i++)
{
echo $response[$i]['message'] . "<br>" ;
echo $response[$i]['date'] . "<br>" ;
echo $response[$i]['sender'] . "<br>" ;
echo $response[$i]['receiver'] . "<br>" ;
}
You need to respond with all of them in an array like this:
$sql = 'SELECT `message`, `date`, `sender`, `receiver` FROM `usertimes` WHERE `receiver` ="'. $messagesforaccount. '"';
You should only request the fields you need. This improves performances and reduces overhead. Later, you can just push the whole row to the response.
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[] = $row;
}
echo json_encode($response);
} else {
echo " 0 results";
}

Getting all EmployeeID's in dropdown list from mysql database?

In my case, I am getting only the EmployeeId which i have registered latest and not all the employeeId's from the table in database.
Code :
public function getEmployeeId() {
if (!isset($_SESSION["email"]) || !isset($_SESSION["passwrd"])) {
header("Location:index.php");
// Cannot Access this page without Login.
}
if (empty($_POST)) {
$query = mysqli_query($this->connection, "SELECT EmployeeId FROM employeeprofile") or die("Query execution failed: " . mysqli_error());
**while ($row = $query->fetch_assoc()) {**
$id = $row["EmployeeId"];
$_SESSION["id"] = $id;
}
}
}
i am using this session value in tag in my html form.
<select name="EmployeeId" required autofocus class='form-control'>
<option value=""> ----Select----</option>
<?php
if (isset($_SESSION["id"])) {
echo "<option value = " . $_SESSION["id"] . ">" . $_SESSION["id"] . "</option>";
}
?>
</select>
Someone suggested me to check the array , but i am confused.
You're currently overwriting the ID on each iteration. You need to store them in an array in which you append each ID instead:
// Make this session item an array
$_SESSION['id'] = [];
$query = mysqli_query($this->connection, "SELECT EmployeeId FROM employeeprofile") or die("Query execution failed: " . mysqli_error());
while ($row = $query->fetch_assoc()) {
// Push the id to the array
$_SESSION['id'][] = $row["EmployeeId"];
}
Now you need to iterate through the array with the ID's when printing the options:
if (isset($_SESSION["id"])) {
foreach ($_SESSION['id'] as $id) {
echo "<option value='$id'>$id</option>";
}
}
This should work, as long as you have session_start() in the top of your scripts.
I would probably not use sessions to store results like this, but I don't know enough of your code to be able to give you a good solution.
i thik the problem is that you should retrieve data in array from query and you can apply foreach loop to print the employee.
first get all the employee
$query = mysqli_query($this->connection, "SELECT EmployeeId FROM employeeprofile") or die("Query execution failed: " . mysqli_error());
$result = query($query);
now print the retrieved employee in option field
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value=" . $row["id"] . ">" . $row["id"] . "</option>"
}
} else {
echo "<option value="">No result found.</option>"
}
For me wouldn't advise to use sessioning, then to populate your select input, you do the below code, this is just a method of doing this anyway
public function getEmployeeId() {
if (!isset($_SESSION["email"]) || !isset($_SESSION["passwrd"])) {
header("Location:index.php");
// Cannot Access this page without Login.
}
$ids = array();
if (empty($_POST)) {
$query = mysqli_query($this->connection, "SELECT EmployeeId FROM employeeprofile") or die("Query execution failed: " . mysqli_error());
while($row = mysqli_fetch_array($query)){
$ids[] = $row['EmployeeId']; //we populate our array here
}
}
return $ids; //return the array here
}
from your html you do this
<select>
<option value="">Select</option>
<?php
$ids = getEmployeeId();
for($i=0;$i<count($ids); $i++){
?>
<option value="<?php echo $ids[$i];?>"><?php echo $ids[$i];?></option>
<?php }?>
</select>
It is because, you are putting only last value of array in $_SESSION["id"] variable
Change $_SESSION["id"] = $id; to $_SESSION["id"][] = $id;
and to print
if (isset($_SESSION["id"])) {
foreach($_SESSION["id"] as $v){
echo "<option value ='" . $v . "'>" . $v."</option>";
}
}

How to make a PHP page have two "column" regions?

Basically I'm doing digital signage and I'm trying to get names to be pulled from a MySQL database to a PHP page. Right now its all centered in one column, but I want the results to be in two columns side by side. How can I do this?
$sql = "SELECT * FROM donor WHERE DonationAmount = 5000 AND Category = '1' or DonationAmount = 5000 AND Category IS NULL ORDER BY LastName ASC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
if(empty($row['DisplayName']))
{
// it's empty!
if(empty($row['FirstName'])){
echo $row['LastName']. "<br>";
}
else{
echo $row["LastName"]. ", " . $row["FirstName"]. "<br>";
}
}else{
// Do stuff with the field
echo $row["DisplayName"]. "<br>";
}
}
} else {
}
Basically I want this data to be spread across two columns instead of 1 single page.
output the strings like this:
echo "<span style=\"width:50%;float:left;\">".$row['LastName']."</span>";
do not forget to remove <br /> from each output
You can use tables, and count the rows to determine if you need to start a new table row.
$i = 0;
$total_rows = $result->num_rows;
echo "<table><tr>";
while($row = mysqli_fetch_assoc($result)) {
// test if the DisplayName field is empty or not
echo "<td>";
if(empty($row['DisplayName']))
{
// it's empty!
if(empty($row['FirstName'])){
echo $row['LastName'];
}
else{
echo $row["LastName"]. ", " . $row["FirstName"];
}
}else{
// Do stuff with the field
echo $row["DisplayName"]. "";
}
echo "</td>";
$i++;
if($i % 2 == 0 && $i != $total_rows) {
echo "</tr><tr>";
}
}
echo "</tr></table>";
if your content is in <div id="myDiv"> use this JS function and call it after the content loads
function splitValues() {
var output = "";
var names = document.getElementById('myDiv').innerHTML.split("<br>");
for(var i in names) {
output += "<span style=\"width:50%;float:left;display:inline-block;text-align:center;\">"+names[i]+"</span>";
}
document.getElementById('myDiv').innerHTML = output;
}

Combine multiple POSTs and adding it to table

Here is my code to add multiple types to table. I want to combine areas, location, types and add them in the table at once. I think this just wont work if(!empty($_POST['types'] && $_POST[''] && $_POST[''] ) Thanks!
if(!empty($_POST['types'])) {
$values = array();
foreach($_POST['types'] as $typ_id) {
$values[] = sprintf('(%d, %d)', $station_id, $typ_id);
}
$query = 'INSERT IGNORE INTO station_typ_tab
(station_id, typ_id, area_id, location_id)
VALUES ' .
implode(',', $values);
mysql_query($query, $db) or die(mysql_error($db));
}
EDIT: here is part of code for types[] and same is for areas and location
<td>Types:<br/> <small>CTRL + click to set multiple pollutants</em></small>
</td>
<td>
<?php
$query = 'SELECT typ_id, typ FROM typ_tab ORDER BY typ ASC';
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) > 0) {
echo '<select multiple name="types[]">';
while ($row = mysql_fetch_array($result)) {
if (isset($station_typ[$row['typ_id']])) {
echo '<option value="' . $row['typ_id'] . '"
selected="selected">';
} else {
echo '<option value="' . $row['typ_id'] .'">';
}
echo $row['typ'] . '</option>';
}
echo '</selected>';
} else {
echo '<p><strong>Databaza je prazdna... Enter database</strong></p>';
}
mysql_free_result($result);
how to combine $_POST for types, location and areas if they comes from different selecting input. something like if(!empty($_POST['types'] && $_POST['areas'] && $_POST['location']) ){ $values = array(); foreach( NEW VARIABLE as $typ_id && area_id &&location_id) { $values[] = sprintf('(%d, %d, %d, %d)', $station_id, $typ_id, area_id, location_id); if it is possible to do it like this
to combine in IF try to use
if((!empty($_POST['types'])) && (!empty($_POST['area'])) && (!$_POST['location'])));

For each results- Mysql - JSON

How i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}
Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag
$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.

Categories