I'm trying to upload an excel file to a mysql DB using PHP. I've got this working.
However, if I refresh the page or upload again another file, it gets duplicated.
I would like before it uploads a new file to clear (truncate) the table and then insert the new data.
Bue I cannot find where to put or how to put the TRUNCATE TABLE existencias_2018; if the Submit button is clicked and before it inserts the data.
Another issue is the refreshing thing. It is a way to stop the refresh after I've uploaded the data? Or a way that refreshing doesn't duplicate it?
So in summary the help i need is:
Where to put and how the TRUNCATE TABLE existencias_2018;.
Stop duplicating data if page gets refreshed.
Here is my piece of code:
<?php
$conn = mysqli_connect("localhost","root","","papa");
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"])){
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++){
$Reader->ChangeSheet($i);
foreach ($Reader as $Row){
$model = "";
if(isset($Row[0])) {
$model = mysqli_real_escape_string($conn,$Row[0]);
}
$cup = "";
if(isset($Row[1])) {
$cup = mysqli_real_escape_string($conn,$Row[1]);
}
$color = "";
if(isset($Row[1])) {
$color = mysqli_real_escape_string($conn,$Row[2]);
}
$description = "";
if(isset($Row[1])) {
$description = mysqli_real_escape_string($conn,$Row[3]);
}
$size36 = "";
if(isset($Row[1])) {
$size36 = mysqli_real_escape_string($conn,$Row[4]);
}
$size38 = "";
if(isset($Row[1])) {
$size38 = mysqli_real_escape_string($conn,$Row[5]);
}
$size40 = "";
if(isset($Row[1])) {
$size40 = mysqli_real_escape_string($conn,$Row[6]);
}
$size42 = "";
if(isset($Row[1])) {
$size42 = mysqli_real_escape_string($conn,$Row[7]);
}
$size44 = "";
if(isset($Row[1])) {
$size44 = mysqli_real_escape_string($conn,$Row[8]);
}
$size46 = "";
if(isset($Row[1])) {
$size46 = mysqli_real_escape_string($conn,$Row[9]);
}
$size48 = "";
if(isset($Row[1])) {
$size48 = mysqli_real_escape_string($conn,$Row[10]);
}
$size50 = "";
if(isset($Row[1])) {
$size50 = mysqli_real_escape_string($conn,$Row[11]);
}
$size52 = "";
if(isset($Row[1])) {
$size52 = mysqli_real_escape_string($conn,$Row[12]);
}
$size54 = "";
if(isset($Row[1])) {
$size54 = mysqli_real_escape_string($conn,$Row[13]);
}
if (!empty($model) || !empty($cup) || !empty($color) || !empty($description) || !empty($size36) || !empty($size38) || !empty($size40) || !empty($size42) || !empty($size44) || !empty($size46) || !empty($size48) || !empty($size50) || !empty($size52) || !empty($size54)) {
$query = "insert into existencias_2018(model,cup,color,description,size36,size38,size40,size42,size44,size46,size48,size50,size52,size54) values('".$model."','".$cup."','".$color."','".$description."','".$size36."','".$size38."','".$size40."','".$size42."','".$size44."','".$size46."','".$size48."','".$size50."','".$size52."','".$size54."')";
$result = mysqli_query($conn, $query);
if (! empty($result)) {
$type = "success";
$message = "Datos de Excel importados en la base de datos satisfactoriamente";
} else {
$type = "error";
$message = "Ha habido un problema al importar los datos de Excel";
}
}
}
}
}else{
$type = "error";
$message = "Tipo de archivo invalido. Suba un archivo de Excel.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial;
width: 1000px;
}
.outer-container {
background: #F0F0F0;
border: #e0dfdf 1px solid;
padding: 40px 20px;
border-radius: 2px;
}
.btn-submit {
background: #333;
border: #1d1d1d 1px solid;
border-radius: 2px;
color: #f0f0f0;
cursor: pointer;
padding: 5px 20px;
font-size:0.9em;
}
.tutorial-table {
margin-top: 40px;
font-size: 0.8em;
border-collapse: collapse;
width: 100%;
}
.tutorial-table th {
background: #f0f0f0;
border-bottom: 1px solid #dddddd;
padding: 8px;
text-align: left;
}
.tutorial-table td {
background: #FFF;
border-bottom: 1px solid #dddddd;
padding: 8px;
text-align: left;
}
#response {
padding: 10px;
margin-top: 10px;
border-radius: 2px;
display:none;
}
.success {
background: #c7efd9;
border: #bbe2cd 1px solid;
}
.error {
background: #fbcfcf;
border: #f3c6c7 1px solid;
}
div#response.display-block {
display: block;
}
</style>
</head>
<body>
<h2>Importar existencias actualizadas</h2>
<div class="outer-container">
<form action="" method="post"
name="frmExcelImport" id="frmExcelImport" enctype="multipart/form-data">
<div>
<label>Buscar archivo Excel</label>
<input type="file" name="file" id="file" accept=".xls,.xlsx">
<button type="submit" id="submit" name="import" class="btn-submit">Importar</button>
</div>
</form>
</div>
<div id="response" class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>"><?php if(!empty($message)) { echo $message; } ?></div>
<?php
$sqlSelect = "SELECT * FROM existencias_2018";
$result = mysqli_query($conn, $sqlSelect);
if (mysqli_num_rows($result) > 0){
?>
<table class='tutorial-table'>
<thead>
<tr>
<th>Modelo</th>
<th>Copa</th>
<th>Color</th>
<th>Descripcion</th>
<th>36</th>
<th>38</th>
<th>40</th>
<th>42</th>
<th>44</th>
<th>46</th>
<th>48</th>
<th>50</th>
<th>52</th>
<th>54</th>
</tr>
</thead>
<?php
$sql = "TRUNCATE TABLE existencias_2018";
while ($row = mysqli_fetch_array($result)) {
?>
<tbody>
<tr>
<td><?php echo $row['model']; ?></td>
<td><?php echo $row['cup']; ?></td>
<td><?php echo $row['color']; ?></td>
<td><?php echo $row['description']; ?></td>
<td><?php echo $row['size36']; ?></td>
<td><?php echo $row['size38']; ?></td>
<td><?php echo $row['size40']; ?></td>
<td><?php echo $row['size42']; ?></td>
<td><?php echo $row['size44']; ?></td>
<td><?php echo $row['size46']; ?></td>
<td><?php echo $row['size48']; ?></td>
<td><?php echo $row['size50']; ?></td>
<td><?php echo $row['size52']; ?></td>
<td><?php echo $row['size54']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</body>
</html>
Is that what you want ?
<?php
$conn = mysqli_connect("localhost","root","","papa");
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"])){
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
// Looks like we have a correct file to upload.
// Let's TRUNCATE the table first :
$query = "TRUNCATE TABLE existencias_2018;";
mysqli_query($conn, $query);
// OK, table is empty, proceed with upload....
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++){
$Reader->ChangeSheet($i);
foreach ($Reader as $Row){
$model = "";
if(isset($Row[0])) {
$model = mysqli_real_escape_string($conn,$Row[0]);
}
// and so on...
Related
Recently, I discovered that the exam scores of students are not displaying anymore in a particular class (PRE-NURSERY).
Going back to the form where results are added, I see that the results have been repopulated and are already stored in the database.
However, they are not been displayed in the view. I wonder what must be wrong.
model
public function getRecentmtGradesRN($id)
{
$this->db->select('*');
$this->db->where('student_id', $id);
return $this->db->get('mtscores_rn')->result();
}
controller
public function view($id)
{
if (!$this->rbac->hasPrivilege('student', 'can_view')) {
access_denied();
}
$data['title'] = 'Student Details';
$student = $this->student_model->get($id);
$gradeList = $this->grade_model->get();
if($class_id == 2 || $class_id == 3) //see here
{
$subjectmtScores = $this->student_model->getRecentmtGradesRN($id);
}
else
{
$subjectmtScores = $this->student_model->getRecentmtGrades($id);
}
$studentSession = $this->student_model->getStudentSession($id);
$timeline = $this->timeline_model->getStudentTimeline($id, $status = '');
$data["timeline_list"] = $timeline;
$student_session_id = $studentSession["student_session_id"];
$student_session = $studentSession["session"];
$data['sch_setting'] = $this->sch_setting_detail;
$data['adm_auto_insert'] = $this->sch_setting_detail->adm_auto_insert;
$current_student_session = $this->student_model->get_studentsession($student['student_session_id']);
$data["session"] = $current_student_session["session"];
$student_due_fee = $this->studentfeemaster_model->getStudentFees($student['student_session_id']);
$student_discount_fee = $this->feediscount_model->getStudentFeesDiscount($student['student_session_id']);
$data['student_discount_fee'] = $student_discount_fee;
$data['student_due_fee'] = $student_due_fee;
$siblings = $this->student_model->getMySiblings($student['parent_id'], $student['id']);
$student_doc = $this->student_model->getstudentdoc($id);
$data['student_doc'] = $student_doc;
$data['student_doc_id'] = $id;
$category_list = $this->category_model->get();
$data['category_list'] = $category_list;
$data['gradeList'] = $gradeList;
$data['subjectmtScores'] = $subjectmtScores; //see here
//var_dump($subjectmtScores); die();
$data['student'] = $student;
$data['siblings'] = $siblings;
$class_section = $this->student_model->getClassSection($student["class_id"]);
$data["class_section"] = $class_section;
$session = $this->setting_model->getCurrentSession();
$studentlistbysection = $this->student_model->getStudentClassSection($student["class_id"], $session);
$data["studentlistbysection"] = $studentlistbysection;
$data['guardian_credential'] = $this->student_model->guardian_credential($student['parent_id']);
$data['reason'] = $this->disable_reason_model->get();
if ($student['is_active'] = 'no') {
$data['reason_data'] = $this->disable_reason_model->get($student['dis_reason']);
}
// //var_dump($data['teacher_comment']);
$this->load->view('layout/header', $data);
$this->load->view('student/studentShow', $data);
$this->load->view('layout/footer', $data);
}
view
<table class="table table-bordered" style="border: 1px solid black;">
<caption class="text-center">ACADEMIC PERFORMANCE</caption>
<thead>
<tr style="border: 1px solid black;">
<th style="border: 1px solid black; font-size:11px;width:120px;text-align:center;">
SUBJECTS
</th>
<th style="border: 1px solid black; font-size:11px;text-align:center;">CLASS
EXPECTATION
</th>
<th style="border: 1px solid black;font-size:11px;text-align:center;">MILESTONE
ACHIEVED
</th>
<th style="border: 1px solid black;font-size:11px;text-align:center;">REMARKS</th>
</tr>
</thead>
<tbody>
<?php $i = 1;
$total = 0;
$count = count($subjectmtScores);
foreach ($subjectmtScores as $value) { ?>
<?php
$mt_tot_score = $value->mt_ca1 + $value->mt_ca2 + $value->mt_ca3 + $value->mt_ca4 + $value->mt_affective + $value->mt_psychomotor + $value->mt_exam;
if ($mt_tot_score >= 80) {
$grade = 'A';
$remark = 'EXCELLENT';
} elseif ($mt_tot_score >= 70 && $mt_tot_score <= 79.99) {
$grade = 'B';
$remark = 'VERY GOOD';
} elseif ($mt_tot_score >= 60 && $mt_tot_score <= 69.99) {
$grade = 'C';
$remark = 'GOOD';
} elseif ($mt_tot_score >= 50 && $mt_tot_score <= 59.99) {
$grade = 'E';
$remark = 'PASS';
} elseif ($mt_tot_score >= 40 && $mt_tot_score <= 49.99) {
$grade = 'F';
$remark = 'FAIR';
} elseif ($mt_tot_score >= 0 && $mt_tot_score<= 39.99) {
$grade = 'FL';
$remark = 'FINAL LETTER GRADE';
}
?>
<?php
$total += $mt_tot_score;
?>
<tr style="border: 1px solid black;">
<td style="border: 1px solid black;font-size:12px;text-align:left;height:30px;"><?php echo $CI->GetSubjectNameWithID($value->subject_id); ?></td>
<td style="border: 1px solid black;font-size:12px;text-align:center;"><?php echo $value->mt_ca1; ?></td>
<td style="border: 1px solid black;font-size:12px;text-align:center;"><?php echo $value->mt_ca2; ?></td>
<td style="border: 1px solid black;font-size:12px;text-align:left;white-space:nowrap;"><?php echo $value->mt_ca3; ?></td>
</tr>
<?php $i++;
} ?>
</tbody style="
white-space: nowrap;
">
</table>
Ok i edit my question i think i understand more now how to build a question.
The website: bit DOT ly/1MHItEH
I want to run a php code when span 3 is between 5 & 9.
The code which outputs this is $players and in the bottom there is a html output code
<td><span style='text-shadow: 0 0 10px #ffca00; color: #ffca00; font-size: 20pt;'>". $players ."</span></td>
This php code outputs a html table with different values for every added server.
For example if i add a new server to servers.php it will create a new span for that server with new values. So basicly it reads and outputs different values for every server.
So how can i just run extra php code if the span 3 is between 5 & 9?
<html>
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
tr td, tr th { text-align: center !important; }
tr td.motd, tr th.motd { text-align: left !important; }
</style>
</head>
<body style="width: 100%; margin: 0 auto; height: 20px; ">
<table class='table table-bordered table-striped'>
</br>
<?php
error_reporting(0);
function openserveriai() {
}
function closeserveriai() {
}
function getnextstring(&$data) {
$temp="";
$counter=0;
while (ord($data[$counter++])!=0) $temp.=$data[$counter-1];
$data=substr($data,strlen($temp)+1);
return $temp;
}
function getnextbytevalue(&$data) {
$temp=ord($data[0]);
$data=substr($data,1);
return $temp;
}
function addServer($ip) {
$map = '';
$players = '';
$maxplayers = '';
$servername = '';
$output = '';
$live_server = '0';
$packet = '0';
$packet = "\xFF\xFF\xFF\xFFTSource Engine Query\x00";
$live_server = fsockopen("udp://".$ip);
if(!$live_server)
{
$output = "Off";
}
else
{
fwrite($live_server, $packet);
socket_set_timeout($live_server,1,0);
$junk = fread($live_server,5);
$status = socket_get_status($live_server);
$do = 1;
$server_info= "";
while($do)
{
$str_1 = fread($live_server,1);
$server_info .= $str_1;
$status = socket_get_status($live_server);
if($status["unread_bytes"] == 0) {$do = 0;}
}
fclose($live_server);
if (strlen($server_info) > 0)
{
$success = 1;
$junk = getnextstring($server_info);
$servername = getnextstring($server_info);
$map = getnextstring($server_info);
$junk = getnextstring($server_info);
$junk = getnextstring($server_info);
$players = getnextbytevalue($server_info);
}
if ($players != '') {
$players = $players;
} else {
$players = "0";
}
if ($maxplayers != '')
{
$maxplayers = $maxplayers;
}
else
{
$maxplayers = "0";
}
if ($output != "Full" and $players != "0" or $maxplayers != "0")
{
$output = $output;
}
else
{
$output = "<font color='#FF0000'>Offline</font>";
}
if ($map != '')
{
$map = $map;
}
else
{
$map = "--";
$maxplayers = "--";
$players = "--";
}
if ($servername != '') {
$servername = $servername;
}
else
{
$servername = "--";
}
}
if($players == $maxplayers && $players != '--')
{
$players = "" . $players . "";
}
else if($players > $maxplayers-3 && $players != '--')
{
$players = "" . $players . "";
}
else
{
$players = "" . $players . "";
}
if ( strlen($map) > 19 )
{
$map = substr($map, 0, 19) . '...';
}
echo "
<tbody>
<tr style='background: #10130d;'>
";
if ($map == '--')
{
echo "<td><span style='background-color: #b85c5c; border-radius: .25em; padding: .2em .6em .3em; font-weight: bold; color: #fff; font-size: 10pt;'>Offline</i></span></td>";
}
else
{
echo "<td><span style='background-color: #5cb85c; border-radius: .25em; padding: .2em .6em .3em; font-weight: bold; color: #fff; font-size: 10pt; '>Online</i></span></td>";
}
echo "
<td><span style='color: #fff; font-size: 10pt;'>". $ip ."</span></td>
<td><span style='text-shadow: 0 0 10px #ffca00; color: #ffca00; font-size: 20pt;'>". $players ."</span></td>
</tr>
</tbody>
";
}
openserveriai();
include ('servers.php');
closeserveriai();
?>
</table>
</body>
</html>
You can do something like this
<?php
$total = 5;
if ($total >= 5 && $total <= 9) {
//Between 5 and 9
} else {
// Not between 5 and 9
}
?>
<table class='table table-bordered table-striped'>
<tbody>
<tr>
<td><span>First</span></td>
<td><span>Second</span></td>
<td><span><?php echo $total; ?></span></td>
</tr>
</tbody>
</table>
Then you can call that php page with
require('yourpage.php');
I've encountered a problem which i'll try to describe below...
Let's say i've got a button for each table row (table is created by acquiring the data from the database...). the button sends a massive of values via post.
<button value='$e->eventId|$e->eventType|$e->eventDate|$e->eventPrice|$e->eventDescr' name='editValue'>EDIT</button>
I've written a function to explode the values of the massive and fill the inputs on the same page.
if(!empty($_POST['editValue'])) {
$editValue_fill = explode("|", $_POST["editValue"]);
$eventId = $editValue_fill[0];
$eventType = $editValue_fill[1];
$eventDate = $editValue_fill[2];
$eventPrice = $editValue_fill[3];
$eventDescr = $editValue_fill[4];
}
Next comes the function to edit the row in the database.
function editEvent ($id, $type, $date, $price, $descr){
$mysqli = new mysqli($GLOBALS["serverHost"], $GLOBALS["serverUsername"], $GLOBALS['serverPassword'], $GLOBALS['dbName']);
$stmt = $mysqli->prepare("UPDATE events_archive SET eventType='?', eventDate='?', eventPrice='?', eventDescr='?' WHERE id='?'");
$stmt->bind_param("ssdss", $type, $date, $price, $descr, $id);
$stmt->execute();
header("Refresh:0");
if($stmt->execute()){
$eventNotice="Event successfully updated!";
}else{
$eventNotice = "Failed to save...";
}
return $eventNotice;
}
And, of course, the usage of the function which apparently doesnt work. The page just refreshes and nothing happens.
if(empty($eventTypeError)&& empty($eventDateError)&& empty($eventPriceError) && empty($eventDescrError)
&& isset($_POST['eventType']) && isset($_POST['eventDate']) && isset ($_POST['eventPrice']) && isset
($_POST['eventDescr']) && !empty($eventId)){
$eventNotice = editEvent($eventId, cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}
So basically, gets values from the row -> fills them into inputs in the same page -> if $eventId is set then updates the row, if not - creates a new row (diff. function)
Could anyone give me a tip or help solving the problem? I've been trying to understand the issue and failed dramatically...
<?php
require ("functions.php");
var_dump($_POST);
//kas on sisseloginud, kui ei ole siis
//suunata login lehele
//kas ?logout on aadressireal
if (isset($_GET['logout'])){
session_destroy();
header("Location: login.php");
}
if (!isset ($_SESSION["userId"])){
header("Location: login.php");
}
$confirm = "";
$eventNotice = "";
$eventTypeError = "";
$eventDateError = '';
$eventPriceError = '';
$eventDescrError = '';
$eventType = '';
$eventDescr = '';
$eventPrice = '';
$eventDate = date("Y-m-d");
if (isset ($_POST["eventType"])){
if (empty($_POST['eventType'])){
$eventTypeError = "Please choose the event type!";
} else {
$eventType = $_POST["eventType"];
}
}
if (isset ($_POST ["eventDate"])){
if (empty ($_POST ["eventDate"])){
$eventDateError = "Please choose the date!";
} else {
$eventDate = $_POST["eventDate"];
}
}
if (isset ($_POST ["eventPrice"])){
if (empty ($_POST ["eventPrice"])){
$eventPriceError = "Please type in the price!";
} else {
$eventPrice = $_POST["eventPrice"];
}
}
if (isset ($_POST ["eventDescr"])){
if (empty ($_POST ["eventDescr"])){
$eventDescrError = "Please type in the description!";
}elseif (strlen($_POST["eventDescr"])< 10) {
$eventDescrError = "Description must be longer than 10 symbols!";
$eventDescr = $_POST['eventDescr'];
}else{
$eventDescr = $_POST['eventDescr'];
}
}
$event = getAllEvents();
if(!empty($_POST['delValue'])) {
delEvent($_POST['delValue']);
}
if(!empty($_POST['editValue'])) {
$editValue_fill = explode("|", $_POST["editValue"]);
$eventId = $editValue_fill[0];
$eventType = $editValue_fill[1];
$eventDate = $editValue_fill[2];
$eventPrice = $editValue_fill[3];
$eventDescr = $editValue_fill[4];
echo ($eventId);
echo ($eventDate);
echo ($eventPrice);
echo ($eventType);
echo ($eventDescr);
}
if(empty($eventTypeError)&& empty($eventDateError)&& empty($eventPriceError) && empty($eventDescrError)
&& isset($_POST['eventType']) && isset($_POST['eventDate']) && isset ($_POST['eventPrice']) && isset
($_POST['eventDescr'])){
if(isset($_POST['editValue'])){
$eventNotice = editEvent($eventId, cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}elseif(!isset($_POST['editValue'])){
$eventNotice = newEvent(cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}
}
?>
<html>
<style>
#import "styles.css";
ul.tab {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
ul.tab li {float: left;}
ul.tab li a {
display: inline-block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
transition: 0.3s;
font-size: 17px;
}
ul.tab li a:hover {
background-color: #ddd;
}
ul.tab li a:focus, .active {
background-color: #ccc;
}
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
</style>
<body>
<form method ="post">
<table class="table1">
<tr>
<td style="text-align:center"><h1>Data</h1></td>
</tr>
<tr>
<th><h2>Profile</h2></th>
</tr>
<tr>
<td>
<table class="table2">
<tr>
<td colspan="3"">Welcome <?=$_SESSION['email'];?>!</td>
</tr>
<tr>
<td colspan="3" style="text-align:center">Log out</td>
</tr>
</table>
<tr>
<td>
<tr>
<td>
<ul class="tab">
<li>Add/edit</li>
<li>Archive</li>
</ul>
<div id="Add/edit" class="tabcontent">
<input type="hidden" value='eventId'>
<table class="table2">
<tr>
<td>Event type:<span class = 'redtext'>*</span></td>
<td style="text-align:left">
<select name="eventType">
<?php if(empty($eventType)){?>
<option value="" selected>Choose here</option>
<?php } else { ?>
<option value="">Choose here</option>
<?php } ?>
<?php if($eventType == "Planned service"){?>
<option value="Planned service" selected>Planned service</option>
<?php } else { ?>
<option value="Planned service">Planned service</option>
<?php } ?>
<?php if($eventType == "Unplanned service"){?>
<option value="Unplanned service" selected>Unplanned service</option>
<?php } else { ?>
<option value="Unplanned service">Unplanned service</option>
<?php } ?>
<?php if($eventType == "Fuel checks"){?>
<option value="Fuel checks" selected>Fuel checks</option>
<?php } else { ?>
<option value="Fuel checks">Fuel checks</option>
<?php } ?>
<?php if($eventType == "Tuning"){?>
<option value="Tuning" selected>Tuning</option>
<?php } else { ?>
<option value="Tuning">Tuning</option>
<?php } ?>
<?php if($eventType == "Car accident"){?>
<option value="Car accident" selected>Car accident</option>
<?php } else { ?>
<option value="Car accident">Car accident</option>
<?php } ?>
</select>
</td>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventTypeError?></td></tr>
<tr>
<td>Date:<span class = 'redtext'>*</span></td>
<td style="text-align:left"><input name="eventDate" type ="date" min="1900-01-01" max = "<?=date('Y-m-d'); ?>" value = "<?=$eventDate?>" placeholder="YYYY-MM-DD"></td>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventDateError?></td></tr>
<tr>
<td>Price:<span class = 'redtext'>*</span></td>
<td style="text-align:left"><input type="text" name="eventPrice" placeholder="ex. 15.50" onkeypress="return onlyNumbersWithDot(event);" / value = "<?=$eventPrice?>"></td>
<script type="text/javascript">
function onlyNumbersWithDot(e) {
var charCode;
if (e.keyCode > 0) {
charCode = e.which || e.keyCode;
}
else if (typeof (e.charCode) != "undefined") {
charCode = e.which || e.keyCode;
}
if (charCode == 46)
return true
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventPriceError?></td></tr>
<tr>
<td>Description:<span class = 'redtext'>*</span></td>
<td style="text-align:left"><textarea name="eventDescr" cols="50" rows="10" placeholder="Describe event here..."><?=$eventDescr?></textarea></td>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventDescrError?></td></tr>
<tr>
<td colspan="3" style="text-align:center"><button type ="submit" value = "Submit">Save</button></td>
</tr>
<tr>
<td colspan="3" style="text-align:center"><p class = "redtext"><?=$eventNotice;?></p></td>
</tr>
</table>
</div>
</form>
<form method="post">
<div id="Archive" class="tabcontent">
<table class="table2">
<tr>
<td colspan="3"">
<?php
$html = "<table>";
$html .= "<tr>";
$html .= "<th>Event type</th>";
$html .= "<th>Date</th>";
$html .= "<th>Price(€)</th>";
$html .= "<th>Description</th>";
$html .= "<th>Delete</th>";
$html .= "<th>Edit</th>";
$html .= "</tr>";
foreach($event as $e){
$html .= "<tr>";
$html .= "<td>$e->eventType</td>";
$html .= "<td>$e->eventDate</td>";
$html .= "<td>$e->eventPrice</td>";
$html .= "<td>$e->eventDescr</td>";
$html .= "<td><button style='border:none; background-color: transparent;' value='$e->eventId' name='delValue' onclick=\"return confirm('Do you really want to delete this row?')\"><img src='delete.png' width='20' height='20'></button></td>";
$html .= "<td><button style='border:none; background-color: transparent;' value='$e->eventId|$e->eventType|$e->eventDate|$e->eventPrice|$e->eventDescr' name='editValue'><img src='edit.png' width='20' height='20'></button></td>";
$html .= "</tr>";
}
$html .= "</table>";
echo $html;
?>
</td>
</tr>
</div>
<script>
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>
</td>
</tr>
</table>
</td>
</tr>
</div>
</form>
</body>
</html>
Looking forward to Your help!
Best regards :)
if(isset($_POST['editValue'])){
$eventNotice = editEvent($eventId, cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}
I tried to render a table from MS-SQL Database to Webpage and i get this error.
I'm still new in PHP. Please help
Useraccess.php
<?php
$path = dirname(__FILE__);
require_once(dirname(__FILE__)."/simpleusers/config.inc.php");
$SimpleUsers = new SimpleUsers();
$users = $SimpleUsers->getUsers();
class SimpleUsers
{
private $mysqli , $stmt;
private $conn;
private $sessionName = "SimpleUsers";
public $logged_in = false;
public $userdata;
public $uPassword;
public $salt;
public function getUsers()
{
$sql = "SELECT DISTINCT userId, uUsername, uActivity, uCreated FROM users ORDER BY uUsername ASC";
$stmt = sqlsrv_query($this->conn, $sql);
if( $stmt == false){
throw new Exception("Query Failed:".sqlsrv_errors());
}
$stmt->execute();
$stmt->store_result();
if( $stmt->num_rows == 0){
return array();
}
$users = array();
$i = 0;
while( $stmt->fetch() )
{
$users[$i]["userId"] = $userId;
$users[$i]["uUsername"] = $username;
$users[$i]["uActivity"] = $activity;
$users[$i]["uCreated"] = $created;
$i++;
}
}
}
?>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style type="text/css">
* { margin: 0px; padding: 0px; }
body
{
padding: 30px;
font-family: Calibri, Verdana, "Sans Serif";
font-size: 12px;
}
table
{
width: 800px;
margin: 0px auto;
}
th, td
{
padding: 3px;
}
.right
{
text-align: right;
}
h1
{
color: #FF0000;
border-bottom: 2px solid #000000;
margin-bottom: 15px;
}
p { margin: 10px 0px; }
p.faded { color: #A0A0A0; }
</style>
</head>
<body>
<h1>User administration</h1>
<table cellpadding="0" cellspacing="0" border="1">
<thead>
<tr>
<th>Username</th>
<th>Last activity</th>
<th>Created</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="4" class="right">
Create new user | Logout
</td>
</tr>
</tfoot>
<tbody>
<?php foreach
( $users as $user ): ?>
<tr>
<td><?php echo $user["uUsername"]; ?></td>
<td class="right"><?php echo $user["uActivity"]; ?></td>
<td class="right"><?php echo $user["uCreated"]; ?></td>
<td class="right">Delete | User info | Change password</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
config.inc.php
<?php
$GLOBALS["serverName"] = "DESKTOP-KRF6KT7\SQLEXPRESS";
$GLOBALS["database"] = "SimpleUsers";
$GLOBALS["uid"] = "sa";
$GLOBALS["pwd"] = "twinz0000";
$GLOBALS["connectionInfo"] = array(
"Database"=>$GLOBALS["database"],
"UID"=>$GLOBALS["uid"],
"PWD"=>$GLOBALS["pwd"])
?>
Error Displayed
Warning: sqlsrv_query() expects parameter 1 to be resource, null given in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php on line 26
Notice: Array to string conversion in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php on line 29
Fatal error: Uncaught exception 'Exception' with message 'Query Failed:Array' in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php:29 Stack trace: #0 C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php(8): SimpleUsers->getUsers() #1 {main} thrown in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php on line 29
Your conn class property is not set.
Before you call $stmt = sqlsrv_query($this->conn, $sql); you must set it up in sqlsrv_connect.
Try adding construct:
public function __construct()
{
$this->conn = sqlsrv_connect($GLOBALS["serverName"], $GLOBALS["connectionInfo"]);
}
Useraccess.php
<?php
$path = dirname(__FILE__);
require_once(dirname(__FILE__)."/simpleusers/config.inc.php");
$SimpleUsers = new SimpleUsers();
$users = $SimpleUsers->getUsers();
class SimpleUsers
{
private $mysqli , $stmt;
private $conn;
private $sessionName = "SimpleUsers";
public $logged_in = false;
public $userdata;
public $uPassword;
public $salt;
public $conn=$GLOBALS["conn"] ;
public function getUsers()
{
$sql = "SELECT DISTINCT userId, uUsername, uActivity, uCreated FROM users ORDER BY uUsername ASC";
$stmt = sqlsrv_query($this->conn, $sql);
if( $stmt == false){
throw new Exception("Query Failed:".sqlsrv_errors());
}
$stmt->execute();
$stmt->store_result();
if( $stmt->num_rows == 0){
return array();
}
$users = array();
$i = 0;
while( $stmt->fetch() )
{
$users[$i]["userId"] = $userId;
$users[$i]["uUsername"] = $username;
$users[$i]["uActivity"] = $activity;
$users[$i]["uCreated"] = $created;
$i++;
}
}
}
?>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style type="text/css">
* { margin: 0px; padding: 0px; }
body
{
padding: 30px;
font-family: Calibri, Verdana, "Sans Serif";
font-size: 12px;
}
table
{
width: 800px;
margin: 0px auto;
}
th, td
{
padding: 3px;
}
.right
{
text-align: right;
}
h1
{
color: #FF0000;
border-bottom: 2px solid #000000;
margin-bottom: 15px;
}
p { margin: 10px 0px; }
p.faded { color: #A0A0A0; }
</style>
</head>
<body>
<h1>User administration</h1>
<table cellpadding="0" cellspacing="0" border="1">
<thead>
<tr>
<th>Username</th>
<th>Last activity</th>
<th>Created</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="4" class="right">
Create new user | Logout
</td>
</tr>
</tfoot>
<tbody>
<?php foreach
( $users as $user ): ?>
<tr>
<td><?php echo $user["uUsername"]; ?></td>
<td class="right"><?php echo $user["uActivity"]; ?></td>
<td class="right"><?php echo $user["uCreated"]; ?></td>
<td class="right">Delete | User info | Change password</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
config.inc.php
<?php
$GLOBALS["serverName"] = "DESKTOP-KRF6KT7\SQLEXPRESS";
$GLOBALS["database"] = "SimpleUsers";
$GLOBALS["uid"] = "sa";
$GLOBALS["pwd"] = "twinz0000";
$GLOBALS["connectionInfo"] = array(
"Database"=>$GLOBALS["database"],
"UID"=>$GLOBALS["uid"],
"PWD"=>$GLOBALS["pwd"]);
$GLOBALS["conn"] = sqlsrv_connect($GLOBALS["serverName"], $GLOBALS["connectionInfo"] );
?>
Hope it will help.
I have these two items in my php.ini file enabled:
extension=php_pdo_sqlsrv_53_ts.dll
extension=php_sqlsrv_53_ts.dll
Which is what I had before. Using Wamp Server. PHP 5.3.13 all the same as before. What else am I missing that is not allowing this to connect to the SQL server.
After connection file code.
<?php
$GLOBALS["serverName"] = "localhost";
$GLOBALS["database"] = "SimpleUsers";
$GLOBALS["uid"] = "root";
$GLOBALS["pwd"] = "";
$GLOBALS["connectionInfo"] = array(
"Database"=>$GLOBALS["database"],
"UID"=>$GLOBALS["uid"],
"PWD"=>$GLOBALS["pwd"]);
$conn = sqlsrv_connect($GLOBALS["serverName"], $GLOBALS["connectionInfo"]);
?>
These are the working codes that i have done. the program is about accessing information in an xml file such as student's name,id and marks based on group and team number submitted from a form. there are 2 submit buttons if one button is clicked, it will display with an additional element (pic) and the other one without it. so far so good.
but looking at the php codes, i know that i will be facing problems if there are numerous groups and team numbers. there would be a lot of if-else statements and the codes would be very long. i have tried using foreach but i'm not getting the result that i want. are there anyways to simplify this? i have been searching on the web but it seems that i just don't know how to implement them. quite new to this.
<html><style>
.datagrid table { border-collapse: collapse; text-align: center; width: 100%; }
.datagrid {font: normal 12px/150% Arial, Helvetica, sans-serif;
background: #fff;
overflow: hidden;
border: 4px solid #006699;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
border-radius: 20px; }
.datagrid table td, .datagrid table th { padding: 7px 20px; }
.datagrid table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );
background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');
background-color:#006699; color:#FFFFFF; font-size:15px; font-weight:bold;
border-left: 1px solid #0070A8; }
.datagrid table thead th:first-child { border: none; }
.datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 13px;font-weight: normal; }
.datagrid table tbody .alt td { background: #E1EEF4; color: #00496B; }
.datagrid table tbody td:first-child { border-left: none; }
.datagrid table tbody tr:last-child td { border-bottom: none; }
</style>
<center>
<form action="" method="post" >
<select name="group">
<option value="csa">CSA</option>
<option value="csb">CSB</option>
</select>
Enter team number:<input type="text" name="teamnum" value="">
<input type="submit" name="submit1" value="With Photo">
<input type="submit" name="submit2" value="Without Photo">
</form>
<form action="index.php">
<input type="submit" value="main">
</form>
</center>
</html>
<?php
if (isset($_POST['submit1']) != '') {
$file = "student.xml";
$xml = simplexml_load_file($file) or die("Unable to load XML file!");
if (isset($_POST['group']) && isset($_POST['teamnum']) != '') {
$teamnum = $_POST['teamnum'];
$group = $_POST['group'];
if ($group == 'csa' && $teamnum == '1') {
$name = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/total');
//$photo =$xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/pic');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Photo</th><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2) = each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>1</td>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
else if ($group == 'csa' && $teamnum == '2') {
$name = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/total');
//$photo =$xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/pic');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Photo</th><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2) = each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>1</td>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
else if (isset($_POST['submit2']) != '') {
$file = "student.xml";
$xml = simplexml_load_file($file) or die("Unable to load XML file!");
if (isset($_POST['group']) && isset($_POST['teamnum']) != '') {
$teamnum = $_POST['teamnum'];
$group = $_POST['group'];
if ($group == 'csa' && $teamnum == '1') {
$name = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/total');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2) = each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
else if ($group == 'csa' && $teamnum == '2') {
$name = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/total');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2)= each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
?>
i have found the way to solve this by using foreach
<?php
if (isset($_POST['submit1']) != '') {
$file = "student.xml";
$xml = simplexml_load_file($file) or die("Unable to load XML file!");
if (isset($_POST['group']) && isset($_POST['teamnum']) != '') {
$teamnum = $_POST['teamnum'];
$group = $_POST['group'];
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Photo</th><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
echo "<tbody>";
foreach ($xml->xpath("//student[contains(teamNum, $teamnum) and contains(group, $group)]") as $student) {
echo "<tr class='alt'>";
echo "<td>".$student->picture."</td>";
echo "<td>".$student->name."</td>";
echo "<td>".$student->id."</td>";
echo "<td>".$student->total."</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}else echo 'no data';
} else {
echo "enter a team's number";
}
?>
the trick is in the xpath. it selects all students that contains submitted values. after that it will be as $student and i will be able to output the element values from there.