How to duplicate an array based on a condition using php - php

I have an array that picks from the database the staff_id and display them randomly in a table.
But I want to duplicate the array based on the staff_level, such that junior staffs will be duplicated while senior staff will not be duplicated.
This is to make the Junior staffs appear twice than the senior staff. This is the code:
foreach ($invigilator_array_indexes as $array_index) {
if ($row['level'] == 1){
$invi_array = $invigilators[$array_index]['staffid_pdo'].', ';
$output .=$invi_array;
$output .=$invi_array.concat();
}else {
$invi_array = $invigilators[$array_index]['staffid_pdo'].', ';
$output .=$invi_array;
}
}
Please note:
foreach ($invigilator_array_indexes as $array_index) {
$invi_array = $invigilators[$array_index]['staffid_pdo'].', ';
$output .=$invi_array;
}
outputs the staff_id in a random order originally
All help is welcome and will be appreciated. Thank you in anticipation
full code:
<?php
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$records_per_page = 50;
$from_record_num = ($records_per_page * $page) - $records_per_page;
include_once 'includes/config.php';
include_once 'includes/data.inc_course.php';
include 'includes/shuffle2.php';
$database = new Config();
$db = $database->getConnection();
$product = new Data($db);
$stmt = $product->readAll($page, $from_record_num, $records_per_page);
$num = $stmt->rowCount();
//range declaration
$range = $_POST['range'];
?>
<?php include('includes/header.php');
$output1 = "
<body>
<div id='wrapper'>";
echo $output1;
include('includes/nav.php');
$output2 = "
<!-- Page Content -->
<div id='page-wrapper'>
<div class='container-fluid'>
<div class='row'>
<div class='col-lg-12'>
<h1 class='page-header'>Timetable Details</h1>
</div>
<!-- /.col-lg-12 -->
<!-- niyicode -->
<div class='col-lg-12'>
<p>
<a class='btn btn-primary' href='courses/add.php' role='button'>Add Course</a>
<a class='btn btn-primary fleft' href='staff/add.php' role='button'>Add Staff</a>
</p>";
echo $output2;
if($num>0){
if($range>0){
$query1 = "SELECT staffid_pdo,level FROM staff_list WHERE avail_pdo = 1 ORDER BY id_pdo ASC ";
$invi_stmt = $db->prepare($query1);
$invi_stmt->execute();
$invigilators = $invi_stmt->fetchAll(PDO::FETCH_ASSOC);
//generate an array containing the range of keys in the invigilators resultset we got above
$invigilators_array_range = range(0, (count($invigilators) - 1));
$output = "
<table class= 'table table-bordered table-hover table-striped js-serial' id='printTable'>
<caption>Timetable with number of students</caption>
<thead>
<tr class='success'>
<th style='width: 4%'>#</th>
<th>No. Students</th>
<th>Code</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Venue</th>
<th>Duration</th>
<th>Invigilator</th>
<!-- <th>Edit/Del</th> -->
</tr>
</thead>
<tbody>
";
// echo $output;
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$invigilators_needed = round(($row['snb_pdo'] / $range), 0, PHP_ROUND_HALF_EVEN);
print_r($invigilators_needed);
$date_active = $row['dat_pdo'];
$output .= ' <tr>' ;
$output .= '' ;
$output .= ' <td>'.$row['snb_pdo'].'</td>' ;
$output .= ' <td>'.$row['coscd_pdo'].'</td>' ;
$output .= ' <td>'.$date_active.'</td>' ;
$output .= ' <td>'.$row['starttim_pdo'].'</td>' ;
$output .= ' <td>'.$row['endtim_pdo'].'</td>' ;
$output .= ' <td>'.$row['ven_pdo'].'</td>' ;
$output .= ' <td>'.$row['dur_pdo'].'</td>' ;
$output .= ' <td>';
$invigilator_array_indexes = array_rand($invigilators_array_range, $invigilators_needed);
if (count($invigilator_array_indexes)) {
foreach ($invigilator_array_indexes as $array_index) {
if ($row['level'] == 1){
$invi_array = $invigilators[$array_index]['staffid_pdo'].', ';
$output .=$invi_array;
$output .=$invi_array.clone();
}else {
$invi_array = $invigilators[$array_index]['staffid_pdo'].', ';
$output .=$invi_array;
}
print_r($invi_array);
}
} else $output .= "
<div class='alert alert-danger' role='alert'>
<button type='button' class='close' data-dismiss='alert' aria-label='Close'></button>
Not enough <strong>invigilators!</strong>
</div>
";
$output .= '</td>' ;
// Add more here if appropriate .... ;
$output .= ' </tr>' ;
?>
<?php
// }
}
$output .=' </tbody>
</table>
';
$results->free();
mysqli_close($mysqli);
echo $output;
$page_dom = "index.php";
include_once 'includes/pagination.inc_course.php';
?>
<center><button onclick="printData();" class="btn btn-primary hideprint"> Print </button></center>
<br/>
<?php
//range ending
} else {
?>
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Warning!</strong> No valid range entered. Please enter a valid range here!
</div>
<?php
}
?>
<?php
//if num ending
}
else{
?>
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Warning!</strong> No Data. Please add data to view timetable
</div>
<?php
}
?>
<?php
$output5 = " </div>
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
";
echo $output5;
?>
<!-- echo $output; -->
<?php include('includes/footer.php'); ?>

Related

Filter Search Results from a Dropdown in PHP

I have built a search (https://brawlins.com/oer/index.php) and I want to enable user to be able to select filters to limit the search results after their initial search. I have the filters populated in a dropdown menu on my search page (https://brawlins.com/oer/search.php?term=) but I am not sure how to filter down the results once a user clicks on them. I want the users to be able to select multiple options as well. I create a class to store the filters. Below is the code from my filter class:
<?php
class filterContentProvider {
private $conn;
public function __construct($conn) {
$this->conn = $conn;
}
public function getType ($conn) {
$query = $this->conn->prepare("SELECT type, COUNT(*) as total FROM oer_search GROUP BY type");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>Type</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - Type</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
//$filterHTML .= "<option value=''>- Type -</option>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$type = $row["type"];
$total = number_format($row["total"]);
$filterHTML .= "<a class='dropdown-item' href='search.php?type=$type'>$type ($total)</a>";
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
public function getSubject ($conn) {
$query = $this->conn->prepare("SELECT subject, COUNT(*) as total FROM oer_search GROUP BY subject");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>Subject</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - Subject</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$subject = $row["subject"];
$total = number_format($row["total"]);
if ($subject != "") {
$filterHTML .= "<a class='dropdown-item' href='search.php?subject=$subject'>$subject ($total)</a>";
}
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
public function getLicense ($conn) {
$query = $this->conn->prepare("SELECT license, COUNT(*) as total FROM oer_search GROUP BY license");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>License</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - License</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$license = $row["license"];
$total = number_format($row["total"]);
if ($license != "") {
$filterHTML .= "<a class='dropdown-item' href='index-test.php?license=$license'>$license ($total)</a>";
}
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
public function getReviewed ($conn) {
$query = $this->conn->prepare("SELECT review, COUNT(*) as total FROM oer_search GROUP BY review");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>Reviewed</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - Reviewed</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$review = $row["review"];
$total = number_format($row["total"]);
if ($review != "") {
$filterHTML .= "<a class='dropdown-item' href='index-test.php?review=$review'>$review ($total)</a>";
}
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
public function getOrigin ($conn) {
$query = $this->conn->prepare("SELECT source, COUNT(*) as total FROM oer_search GROUP BY source");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>Source</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - Source</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$source = $row["source"];
$total = number_format($row["total"]);
if ($source != "") {
$filterHTML .= "<a class='dropdown-item' href='index-test.php?source=$source'>$source ($total)</a>";
}
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
}
?>
Here is the code I am using on my search.php page. Any help would be much appreciated.
<?php
include("config.php");
include("classes/siteResultsProvider.php");
include("classes/imageResultsProvider.php");
include("classes/filterContentProvider.php");
include("classes/filterImageProvider.php");
if(isset($_GET["term"])){
$term = $_GET["term"];
}
if(isset($_GET["collection"])){
$collection = $_GET["collection"];
}
else {
$collection = "open_content";
}
$page = isset($_GET["page"]) ? $_GET["page"] : 1;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>SOAR</title>
<?php
include("header.php");
?>
<div class="wrapper">
<div class="header">
<div class="headerContent">
<div class="searchContainer">
<form action="search.php" method="GET">
<div class="searchBarContainer">
<input type="hidden" name="collection" value="<?php echo $collection; ?>">
<input class="searchBox" type="text" name="term" value="<?php echo htmlspecialchars($term, ENT_QUOTES) ?>" aria-label="search box">
<button class="searchButton">
<img src="images/search-icon.png" alt="search icon">
</button>
</div>
</form>
</div>
</div><!--end of headerContent-->
<div class="tabsContainer">
<ul class="tabList">
<li class="<?php echo $collection == 'open_content' ? 'active' : '' ?>">
</i> Open Content
</li>
<li class="<?php echo $collection == 'images' ? 'active' : '' ?>">
</i> Images
</li>
</ul>
</div>
</div><!--end of header-->
<!-------------------------beginning of main section where seach results will display-------------------------->
<?php
if($collection == "open_content") {
$filters = new filterContentProvider($conn);
}
else {
$filters = new filterImageProvider($conn);
}
if($collection == "open_content") {
$filterType = $filters->getType($conn);
$filterSubject = $filters->getSubject($conn);
$filterOrigin = $filters->getOrigin($conn);
$fitlerLicense = $filters->getLicense($conn);
$filterReviewed = $filters->getReviewed($conn);
echo "<div class='filterContainer'>
<div class='filterContent'>
<div class='filter'>
$filterType
</div>
<div class='filter'>
$filterSubject
</div>
<div class='filter'>
$filterOrigin
</div>
<div class='filter'>
$fitlerLicense
</div>
<div class='filter'>
$filterReviewed
</div>
</div>
</div>";
}
else {
$imageFilterOrigin = $filters->getImageOrigin($conn);
$imageFilterLicense = $filters->getImageLicense($conn);
echo "<div class='filterContainer'>
<div class='filterContent'>
<div class='filter'>
$imageFilterOrigin
</div>
<div class='filter'>
$imageFilterLicense
</div>
</div>
</div>";
}
?>
<div class="mainResultsSection">
<?php
if($collection == "open_content") {
$resultsProvider = new siteResultsProvider($conn);
$pageSize = 25;
}
else {
$resultsProvider = new imageResultsProvider($conn);
$pageSize = 50;
}
$numResults = $resultsProvider->getNumResults($term);
echo "<p class='resultsCount'>" . number_format($numResults) . " results found</p>";
echo $resultsProvider->getResultsHTML($page, $pageSize, $term);
?>
</div>
<div class="paginationContainer">
<div class="pageButtons">
<div class="pageNumberContainer">
<img src="images/pageStart.png" alt="Start of page image">
</div>
<?php
$pagesToShow = 10;
$numPages = ceil($numResults / $pageSize);
$pagesLeft = min($pagesToShow, $numPages);
$currentPage = $page - floor($pagesToShow / 2);
if($currentPage < 1) {
$currentPage = 1;
}
if($currentPage + $pagesLeft > $numPages + 1) {
$currentPage = $numPages + 1 - $pagesLeft;
}
while($pagesLeft != 0 && $currentPage <= $numPages) {
if($currentPage == $page) {
echo "<div class='pageNumberContainer'>
<img src='images/pageSelected.png' alt='selected page page image'/>
<span class='pageNumber'>$currentPage</span>
</div>";
}
else {
echo "<div class='pageNumberContainer'>
<a href='search.php?term=$term&collection=$collection&page=$currentPage'>
<img src='images/page.png' alt='pages image'/>
<span class='pageNumber'>$currentPage</span>
</a>
</div>";
}
$currentPage++;
$pagesLeft--;
}
?>
<div class="pageNumberContainer">
<img src="images/pageEnd.png" alt="End of page image">
</div>
</div>
</div><!--end of pagination container-->
</div><!--end of wrapper-->
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox#3.5.7/dist/jquery.fancybox.min.js"></script>
<script src="https://unpkg.com/masonry-layout#4/dist/masonry.pkgd.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
It seems like you'd want to do a couple of things to get this working.
If you want the results to be asynchronous:
Add an onchange event to you select inputs. (something like onchange="addFilter('type', this.value)") See https://www.w3schools.com/jsref/event_onchange.asp
Have the onchange function (addFilter) send the filters and query string back to your PHP script via an AJAX request. If you're using jQuery, the get method would work for you. https://api.jquery.com/jquery.get/
Pull the new results in PHP using the $_GET parameters you've passed. (Like you are already doing in your script.) You'll want to echo out just the results--not the navigation and other elements of the page.
Update the search results on the page using (something like $('#myContainer').html(results); in jQuery)
Additionally, it would be good to update the URL params in the location bar How do I modify the URL without reloading the page?
Here's a really simple example:
test.php
<?php
// Look up the results here
// You'll probably want to do something more performant that this; it's just a lazy example. :)
// ...
$query = $this->conn->prepare("SELECT type, COUNT(*) as total FROM oer_search WHERE type LIKE :type AND subject LIKE :subject GROUP BY type");
$query->execute([
'type' => isset($_GET['type'] ? $_GET['type'] : '%',
'subject' => isset($_GET['subject'] ? $_GET['subject'] : '%',
]);
// ...
?>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="jquery-3.4.1.min.js"></script>
<script>
function addFilter(name, value) {
var url = '/test.php?';
var urlParams = new URLSearchParams(window.location.search);
var keys = urlParams.keys();
for(key of keys) {
if (key == name) {
continue;
}
url += key + '=' + urlParams.get(key) + '&';
}
url += name + '=' + value;
window.history.pushState({}, "", );
$.get(url, function(data) {
$('#results').html(data);
});
}
</script>
</head>
<body>
<select onchange="addFilter('type', this.value)">
<option></option>
<option>value 1</option>
<option>value 2</option>
</select>
<select onchange="addFilter('subject', this.value)">
<option></option>
<option>value 1</option>
<option>value 2</option>
</select>
<div id="results"></div>
</body>
</html>
If you don't care/want the page to reload:
Just make the onchange event submit the form with the search parameters again. If you use jQuery, the submit method would work. Be sure to select the options appropriately in the select inputs, or they'll clear out each time (making it impossible to set more than one).

half data insert but remaining data not update that perticular session pass

there is data entered in foreach loop but not insert into database there is half data insert into database but there is no work foreach loop.....after insert half data , theres not update remaining half data.....why this happen
the code is
<?php
include_once('config.php');
if(isset($_POST["email_verify_btn"])) {
$email = $_POST["email_verify"];
$i = 1;
if(strpos($email,"\n")) {
$text = explode("\n",$email);
foreach ($text as $abc) {
$i++;
$status = 1;
$c_by = 1;
$c_date = date('Y-m-d H:i:s');
$c_ip = $_SERVER['REMOTE_ADDR'];
$_SESSION['date_time'] = $c_date;
$insert = $connect->query("INSERT INTO `email_verify_list`(`primary_email`,`session`,`status`,`created_by`, `created_date`, `created_ip`) VALUES ('$abc','".$_SESSION['date_time']."','$status','$c_by','$c_date','$c_ip')");
if($insert) {
$select_status = $connect->query("SELECT * from `email_verify_list` where session='".$_SESSION['date_time']."'");
$fetch_selected_status = $select_status->fetch_assoc();
$fetch_email= $fetch_selected_status['primary_email'];
if(filter_var($fetch_email, FILTER_VALIDATE_EMAIL)) {
function domain_exists($fetch_email)
{
$domain = substr(strrchr($fetch_email, "#"), 1);
$arr = #dns_get_record($domain, DNS_MX);
if ($arr[0]['host'] == $domain && !empty($arr[0]['target'])) {
return $arr[0]['target'];
}
}
if(domain_exists($fetch_email)){
$domain = substr(strrchr($fetch_email, "#"), 1);
$data = #dns_get_record($domain, DNS_MX);
if($data) {
$status = "email id is valid";
}
if (is_array($data) || is_object($data)) {
foreach ($data as $key1) {
$host = $key1['host'];
$target = $key1['target'];
$target_ip = gethostbyname($key1['target']);
}
}
} else {
$status = "mx recored not exist";
}
} else {
$status = "not in syntax" ;
}
$insert_all_data = $connect->query("UPDATE `email_verify_list` SET `host_name`='$host',`target`='$target',`target_ip`='$target_ip',`status`='$status' WHERE session='".$_SESSION['date_time']."'");
if($insert_all_data) {
echo "<script>alert('successfully');</script>";
} else {
echo "<script>alert('!!!!!not successfully');</script>";
}
}
}
}
}
?>
<form method="post" action="" >
<div class="tab-content">
<div class="tab-pane padding-20 active slide-left" id="tab1">
<div class="row row-same-height">
<div class="col-md-12">
<div class="padding-30">
<div class="row clearfix">
<div class="col-sm-3">
<div class="form-group form-group-default">
<label><font size="2">ENTER YOUR EMAIL <span class="glyphicon glyphicon-envelope"></span></font></label><br>
<textarea cols="43" rows="9" name="email_verify" style="border-color:white;border-width:thin;padding:4pt;" multiple/></textarea><br>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-3">
<button type="submit" name="email_verify_btn" class="btn btn-lg btn-info" style="padding:11pt;width:200px;"/><span><b><font size="2">SUBMIT</font></b></span></button>
</div>
</div> <br><br>
<div class="row clearfix">
<div class="col-sm-12">
<table width="100%" class="table ">
<tr class="success">
<th>PRIMARY EMAIL <span class="glyphicon glyphicon-envelope"></span></th>
<th>HOST NAME</th>
<th>TARGET</th>
<th>TARGET IP</th>
<th>STATUS</th>
</tr>
<?php
$select = $connect->query("SELECT * from `email_verify_list` where session='".$_SESSION['date_time']."' order by id");
while($row = $select->fetch_assoc()) {
?>
<tr>
<td><?php echo $row['primary_email']; ?></td>
<td><?php echo $row['host_name']; ?></td>
<td><?php echo $row['target']; ?></td>
<td><?php echo $row['target_ip']; ?></td>
<td><?php echo $row['status']; ?></td>
</tr>
<?php } ?>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>

delete image ins database mysql from dashboard php

hi i need help i have problem in my code and i can't figure the solutions please help me .
this is the dashboard:
image dashboard
and this is problem after click on delete:
delete problem
and this is my code php of posts file:
<?php
/*
===========================================================
=== Manage Members Page ===
=== You can add | edit | delete Members from here ===
===========================================================
*/
session_start();
if (isset($_SESSION['Username'])) {
include 'init.php';
$pageTitle = 'Posts';
$do = isset($_GET['do']) ? $_GET['do'] : 'Manage' ;
//Start Manage Page
if ($do == 'Manage'){ // Manage Members Page
$sort = 'ASC';
$sort_arry = array('ASC', 'DESC');
if(isset($_GET['sort']) && in_array($_GET['sort'], $sort_arry)) {
$sort = $_GET['sort'];
}
$stmt2 = $con->prepare("SELECT * FROM posts ORDER BY Ordering $sort");
$stmt2->execute();
$rows = $stmt2->fetchAll();
?>
<h1 class="text-center"> Manage Posts </h1>
<div class="container categories">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-edit"></i> Manage Posts
<div class="ordering pull-right">
<i class="fa fa-sort"> </i>Ordering: [
<a class="<?php if ($sort == 'ASC') { echo 'active'; } ?>" href="?sort=ASC">Asc </a> |
<a class="<?php if ($sort == 'DESC') { echo 'active'; } ?>" href="?sort=DESC">Desc </a>
]
</div>
</div>
<div class="row">
<?php
foreach ($rows as $image) {
echo '<div class="col-md-3 col-sm-4 "><div class="thumbnail">';
echo '<h2 class="h4">'.$image['Name']. '</h2><div class="main">';
echo '<img src="data:image;base64,'.$image['Image'].' " alt="image name" title="image title" width="255" heigth="255">';
echo '</div>';
echo '<table class="table table-bordered">';
echo '<tr>';
echo '<td>' . "<a href='posts.php?do=Edit&id=". $image['ID'] ."' class='btn btn-xs btn-primary'><i class='fa fa-edit'></i> edit</a>" . '</td>';
echo '<td>' . "<a href='posts.php?do=Delete&id=". $image['ID'] ."' class='btn btn-xs btn-danger'><i class='fa fa-close'></i> Delete</a>" . '</td>';
echo '</tr>';
echo '</table>';
echo '</div>';
echo '</div>';
}
?>
</div>
<?php } elseif ($do == 'Add') { //add Member page ?>
<h1 class="text-center"> ajouter un nouveau post </h1>
<div class="container">
<form class="form-horizontal" enctype="multipart/form-data" action="?do=Insert" method="POST">
<!-- start Username fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Titre</label>
<div class="col-sm-10 col-md-8">
<input type="text" name="image-name" class="form-control" autocomplete="off" placeholder="username pour se connecter dans le site Web" required />
</div>
</div>
<!-- end Username fieled -->
<!-- start Password fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Image</label>
<div class="col-sm-10 col-md-8">
<input type="file" name="image" class="form-control" placeholder="mot de passe doit être difficile et complexe" required/>
</div>
</div>
<!-- end Password fieled -->
<!-- start Full name fieled -->
<div class="form-group">
<label class="col-sm-2" for="categorie">Categories:</label>
<div class="col-sm-10 col-md-8">
<select class="form-control" name="categorie">
<?php
$stmt = $con->prepare("SELECT * FROM `categories`");
// Execute the Statments
$stmt->execute();
// Assign to variable
$rows = $stmt->fetchAll();
?>
<?php
foreach ($rows as $cat) {
echo "<option value='" . $cat['ID'] . "'>". $cat['Name'] . "</option>";
}
?>
</select>
</div>
</div>
<!-- end Full name fieled -->
<!-- start submit fieled -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="Ajouter" class="btn btn-primary" />
</div>
</div>
<!-- end submit fieled -->
</form>
</div>
<?php
} elseif ($do == 'Insert') {
//insert Members Page
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<h1 class='text-center'> insert an post </h1>";
echo "<div class='container'>";
// Get variable from the form
$name = $_POST['image-name'];
$image= addslashes($_FILES['image']['tmp_name']);
$image= file_get_contents($image);
$image= base64_encode($image);
$cat = $_POST['categorie'];
//validate the form
$formErrors = array();
if (strlen($name) < 4) {
$formErrors[] = "title name cant be less then <strong> 4 caracter</strong>";
}
if (strlen($name) > 20) {
$formErrors[] = "title name cant be More then <strong> 20 caracter</strong>";
}
if (empty($name)) {
$formErrors[] = "Username Cant Be <strong>Empty</strong>";
}
// loop into eroos array and echo it
foreach ($formErrors as $Error) {
echo "<div class='alert alert-danger'>" . $Error . "</div>";
}
// check if There is no error procced the operations
if (empty($formErrors)) {
// check if user exist in database
$check = checkItem("Username", "users", $user);
if ($check == 1) {
$theMsg = "<div class='alert alert-danger'> Sorry this user is exist </div>";
redirectHome($theMsg, 'back');
} else {
// Insert User info into database
$stmt = $con->prepare("INSERT INTO posts(Name, Image, Cat_id)
VALUES (:name, :image, :cat)");
$stmt->execute(array(
'name' => $name,
'image' => $image,
'cat' => $cat,
));
// echo success message
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Inserted </div> ';
redirectHome($theMsg, 'back', 5);
}
}
} else {
echo "<div class='container'>";
$theMsg = '<div class="alert alert-danger"> Sorry you cant browse this page directely </div>';
redirectHome($theMsg, 'back', 5); // 6 is secend of redirect to page in function
echo "</div>";
}
echo "</div>";
} elseif ($do == 'Edit') { // Edit Page
//check if GET request userid Is numeric & Get The integer value of it
$post = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
//sellect All Data Depend On This ID
$stmt = $con->prepare("SELECT * FROM posts WHERE ID = ? LIMIT 1");
// execute Query
$stmt->execute(array($post));
//fetch the Data
$row = $stmt->fetch();
// The row count
$count = $stmt->rowCount();
// If Ther's Such Id show The Form
if ($count > 0) { ?>
<h1 class="text-center"> Modifier Post </h1>
<div class="container">
<form class="form-horizontal" enctype="multipart/form-data" action="?do=Update" method="POST">
<div class="col-md-6 col-md-offset-3 panel">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>
<!-- start title fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Titre</label>
<div class="col-sm-10 col-md-8">
<input type="text" name="name" class="form-control" autocomplete="off" required value="<?php echo $row['Name']; ?>" >
</div>
</div>
<!-- end title field -->
<!-- start image filed -->
<div class="form-group">
<label class="col-sm-2 control-label">image</label>
<div class="col-sm-10 col-md-8">
<input type="file" name="image" class="form-control" />
</div>
</div>
<!-- end image filed -->
<!-- start Categories filed -->
<div class="form-group">
<label class="col-sm-2" for="categorie">Categories:</label>
<div class="col-sm-10 col-md-8">
<select class="form-control" name="categorie">
<?php
$stmt = $con->prepare("SELECT * FROM `categories`");
// Execute the Statments
$stmt->execute();
// Assign to variable
$rows = $stmt->fetchAll();
?>
<?php
foreach ($rows as $cat) {
echo "<option value='" . $cat['ID'] . "'>". $cat['Name'] . "</option>";
}
?>
</select>
</div>
</div>
<!-- Categories end-->
<!-- start submit fieled -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="sauvegarder" class="btn btn-primary" />
</div>
</div>
<!-- end submit fieled -->
</div>
</form>
</div>
<?php
// if there's No Such id Show Error Message
} else {
echo "<div class='container'>";
$theMsg = "<div class='alert alert-danger'>Theres is no such Id</div>";
redirectHome($theMsg);
echo "</div>";
}
} elseif ($do == 'Update') {
echo "<h1 class='text-center'> mis a jour Membre </h1>";
echo "<div class='container'>";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get variable from the form
$id = $_POST['id'];
$name = $_POST['name'];
$image = addslashes($_FILES['image']['tmp_name']);
$image = file_get_contents($image);
$image = base64_encode($image);
$cat = $_POST['categorie'];
//validate the form
$formErrors = array();
if (empty($name)) {
$formErrors[] = "<div class='alert alert-danger'>Username Cant Be <strong>Empty</strong> </div>";
}
if (empty($image)) {
$formErrors[] = "<div class='alert alert-danger'>FullName Cant Be <strong>Empty</strong></div>";
}
if (empty($cat)) {
$formErrors[] = "<div class='alert alert-danger'>Email Cant Be <strong>Empty</strong></div>";
}
// loop into eroos array and echo it
foreach ($formErrors as $Error) {
echo $Error;
}
// check if There is no error procced the operations
if (empty($formErrors)) {
// Update The Database With This Info
$stmt = $con->prepare("UPDATE posts SET Name = ? , Image = ? , Cat_id = ? WHERE ID = ?");
$stmt->execute(array($name, $image, $cat, $id));
// echo success message
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Updated </div> ';
redirectHome($theMsg, 'back');
}
} else {
$theMsg = '<div class="alert alert-danger">Sorry you cant browse this page directely </div>';
redirectHome($theMsg);
}
echo "</div>";
}
elseif ($do == 'Delete') { // Delete Member Page
echo "<h1 class='text-center'> Delete Membre </h1>";
echo "<div class='container'>";
//check if GET request userid Is numeric & Get The integer value of it
$id = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
//sellect All Data Depend On This ID
$check = checkItem('id', 'posts', $id);
// If Ther's Such Id show The Form
if ($check > 0) {
$stmt = $con->prepare("DELETE FROM users WHERE ID = :id");
$stmt->bindParam(":id", $id);
$stmt->execute();
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Deleted </div> ';
redirectHome($theMsg);
} else {
$theMsg = "<div class='alert alert-danger'>This id not exist</div>";
redirectHome($theMsg);
}
echo "</div>";
}
include $tpl . 'footer.php';
} else {
header('Location: index.php') ;
exit();
}
from the error, id is the problem.
isset($_GET['id']) && is_numeric($_GET['id'])
i think what u want is
(isset($_GET['id']) && is_numeric($_GET['id']) )//close parantheses in wrong position

Form loaded into div w/ AJAX no longer submits

Let me start by apologizing for the information overload. I have no idea what is not working, so I included a little of everything here.
I have a page named jobs.php that shows a table of open 'jobs' on the left side. When the add job button is clicked, the form to add a new job is loaded into the div on the right side of the page using this:
//Get Next Job
$query = "SELECT * FROM jobs WHERE job_id = (SELECT MAX(job_id) FROM jobs)";
$result = $mysqli->query($query) or die($mysqli->error . __LINE__);
$topjob = $result->fetch_assoc();
$nxtjob = $topjob['job_id'] + 1;
<button class="btn btn-primary pull-right ajaxCall" id="addJobBtn" onclick="nxtJob('<?php echo $nxtjob; ?>')">Add Job</button>
function nxtJob(job) {
var nxtjob = job;
$("#jobDetails").html("Loading...");
$.ajax({
type: "GET",
data: {'id':nxtjob},
url: "addjob.php",
async: true,
success: function(data) {
$("#jobDetails").html(data);
}
});
}
The reasoning behind the get variable is that I need the next job # to be used as a value in the form.
The form itself is on addjob.php, and the very simplified version is this:
<?php
require 'database.php';
if (isset($_POST['addNewJob'])) {
$error = '';
//Check Job # for duplicate if manually changed
$job = $_POST['addjob'];
$query = "SELECT job_id from jobs WHERE job_id = '$job'";
$result = $mysqli->query($query) or die($mysqli->error . __LINE__);
if (mysqli_num_rows($result) > 0) {
$error .= '<br/>Job # already exists.'
}
if ($error == '') {
//Set variables for insert
$job = $mysqli->real_escape_string($_POST['addjob']);
$status = $mysqli->real_escape_string($_POST['addstatus']);
$sql = "INSERT INTO jobs (job_id, status)
VALUES ('$job', '$status')";
if (mysqli_query($mysqli, $sql)) {
$validation = '< div class="alert alert-success" > Job ' . $job . ' Successfully Added </div >';
} else {
$validation = '<div class="alert alert-danger" > "ERROR: Could not able to execute' . $sql . mysqli_error($mysqli);
}
} else {
$validation = ' <div class="alert alert - danger">Job Not Added:' . $error . '</div>';
}
?>
<form class="form - horizontal" method="post" id="addJobForm">
<div class="form - group">
<label for="addjob" class="col - sm - 2 control - label">Job #</label>
<div class="col - sm - 4">
<input type="text" class="form - control" name="addjob"
value=" <?php echo $nxtjob; ?>">
</div>
<label for="addstatus" class="col-sm-2 control-label">Status</label>
<div class="col-sm-4">
<?php
$options = array("New", "In Progress", "Waiting for Parts", "Ready for Customer", "Completed");
?>
<select class="form-control" name="addstatus">
<?php foreach ($options as $option): ?>
<option>
<?php echo $option; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<button type="submit" name="addNewJob" id="addNewJob" class="btn btn-primary pull-right">Submit New
Job
</button>
</form>
<?php echo $validation; ?>
When the add job button is clicked on jobs.php (below), the form loads beautifully, but it doesn't work.
<div class="row">
<div class="col-md-4">
<table class="table table-hover" id="jobTable" data-link="row">
<thead>
<tr>
<th class="col-md-2">Job #</th>
<th class="col-md-4">Customer Name</th>
<th class="col-md-6">Description</th>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_array($jobs)) {
// Print out the contents of the entry
date_default_timezone_set('America/Los_Angeles');
$startdate = date("m/d/Y", strtotime($row['started']));
echo '<tr>';
echo '<td><a class="ajaxCall" href="#" rel="' . $row['job_id'] . '"></a>' . $row['job_id'] . '</td>';
echo '<td>' . $row['cust_name'] . '</td>';
echo '<td class="col-lg-2">' . $row['description'] . '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
<div class="col-md-8">
<div id='jobDetails'></div>
</div>
</div>
When I click Submit New Job, the right side of the page simply goes blank. The form disappears, and no new entry is created in the sql table. However, the form works just fine if I use it directly from addjob.php.
I've read about binding after an AJAX call, and I'm guessing it has something to do with that, but I can't seem to get it working. This is my first attempt at AJAX, so any help is appreciated.

Column data changes to different format on download of CSV in PHP. How can I stop this?

I am creating a csv in server using PHP when the page loads. I am appending data to $output which creates the csv during page loading. I have a column which have Account No which are like (6280720003789856). It looks correct in my web page But when I download data as CSV this automatically changes to (6.28072E+15). How can I stop this from changing.
The code is as follows
<?php
$date_from = $_REQUEST['date_from'];
$date_to = $_REQUEST['date_to'];
$procedure = "call contract_compliance_givecentral_test1('".$date_from."','".$date_to."')";
$conn2 = new MyConnection;
$conn2->Connect();
$rs2 = $conn2->ExecSQL($procedure);
$output = '';
$givecentral_contract = "Documents/givecentral_contract.csv";
$filename = $givecentral_contract;
$fp = #fopen($filename, "w+");
$totalRows_rsnf_count = mysqli_num_rows($rs2);
if ($totalRows_rsnf_count > 0)
{
// Show if recordset not empty
?>
<div class="container" style="padding-left: 25px!important;padding-right: 25px!important;" id="printable_area">
<div class="head">Contract Compliance - Givecentral
<ul class="dashboard-icon">
<li><a title="Export to Excel" target="_blank" href="<?php echo
$givecentral_contract ?>">
</a>
</li>
</ul>
</div>
<div id="loader">
<b>Please Wait</b><img src="images/ajax-loader.gif" />
</div>
<table class="data_table table table-striped display" id="example">
<thead>
<tr>
<?php
$amount1=0;
$fields = mysqli_fetch_fields($rs2);
foreach ($fields as $val)
{
echo '<th>'.$val->name.'</th>';
$output .='"'.$val->name;
$output .= '",';
}
$output .="\n";
?>
</tr>
</thead>
<tbody>
<?php
while($row2 = $rs2->fetch_object())
{
?>
<tr class="data_tr">
<?php
foreach($fields as $val)
{
$col_name = $val->name;
?>
<?php
if($col_name == "Account No")
{
?>
<td style="text-align:right!important; width: 20px!important">
<?php
echo $format="$".number_format(round($row2->$col_name),2);
$output .='"'.$format;
$output .= '",';
?>
</td>
<?php
}
else if(($col_name == "Charged Fee")||($col_name == "Expected Fee")))
{
-------
-------
}
?>
<?php
}
$output .="\n";
}
?>
</tr>
</tbody>
</table>
<input type="hidden" name="report_name" value="givecentral_contract"/>
</div>
<?php
} // Show if recordset not empty
else
{
$type = "warning";
$message = "<b>No records found</b>";
include ("includes/announce.inc.php");
}
?>
If you want to displya it in PHP, then use number_format function.
If it's a problem in the Excel, then select column -> right click -> format cells -> number tab and set the format from general to number

Categories