I want to know how to include variables within sql query (PDO) and how to send values into these variables.
because I want to have select options with corresponding values (which are table names in the DB). And when an option is clicked, value will be sent to a declared variable $taxability.
Please be gentle with my delicate brain guys. I really want to learn. It's just that there are times that I really don't understand. :) Thanks!
Question: how to send VALUES of each OPTION, when clicked, to $taxability variable.
please help me to reconstruct something in my code. Thanks
database.php
<?php
class Database
{
private static $dbName = 'reports' ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'root';
private static $dbUserPassword = '';
private static $cont = null;
public function __construct() {
die('Init function is not allowed');
}
public static function connect()
{
// One connection through whole application
if ( null == self::$cont )
{
try
{
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName,
self::$dbUsername,
self::$dbUserPassword);
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect()
{
self::$cont = null;
}
}
?>
tables.php
<form action="POST">
Month:
<select name="month">
<option value="2017_oct">Oct</option>
<option value="2017_nov">Nov</option>
<option value="2017_dec">Dec</option>
</select>
</form>
<table width="100%" class="table table-striped table-bordered table-hover" id="tbltotal">
<thead>
<tr>
<th>DISTRICT</th>
<th>RPU</th>
<th>AREA</th>
<th>MARKET VALUE</th>
<th>ASSESSED VALUE</th>
</tr>
</thead>
<tbody>
</tbody>
<?php
include 'database.php';
$pdo = Database::connect();
$taxability= "";
$sql = ('SELECT
substring(pin,5,2) as District,
count(arpn) as RPU,
sum(area) as AREA,
sum(marketvalue) as MV,
sum(assessedvalue) as AV
FROM **$tablename**
WHERE taxability="$taxability"
group by District ASC');
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['District'] . '</td>';
echo '<td class="RPU">'. $row['RPU'] . '</td>';
echo '<td class="AREA">'. $row['AREA'] . '</td>';
echo '<td class="MV">'. $row['MV'] . '</td>';
echo '<td class="AV">'. $row['AV'] . '</td>';
}
Database::disconnect();
?>
<script type="text/javascript">
var tds = document.getElementById('tbltotal').getElementsByTagName('td');
var sum = 0; sum2 = 0; sum3 = 0;sum4 = 0;
for(var i = 0; i < tds.length; i ++) {
if(tds[i].className == 'RPU') {
sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
}
if(tds[i].className == 'AREA') {
sum2 += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
}
if(tds[i].className == 'MV') {
sum3 += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
}
if(tds[i].className == 'AV') {
sum4 += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
}
}
document.getElementById('tbltotal').innerHTML += '<tr style="font-weight:bold;"><td >total</td><td>' +
sum + '</td><td>' + sum2 +'.00</td><td>' + sum3+ '</td><td>'+sum4+'</td></tr>';
</script>
</table>
Related
I have notification table on my database where the value is using like json.
Here's my table
id | touserid | data
1 2 a:1:{i:0;s:10:"INV-000001";}
2 2 a:1:{i:0;s:10:"INV-000003";}
3 2 a:1:{i:0;s:15:"The Mej Hotel";}
4 1 a:5:{i:0;s:28:"Total Goalsi:1;s:7:"6250000";}
5 1 a:1:{i:0;s:10:"INV-000007";}
I want to use that value in html table, but I don't know how to convert the value to html table in codeigniter
Here's my view code
<table class="table table-dark">
<tbody>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Data</th>
<
</tr>
</thead>
<tbody>
<?php foreach($notifications as $notif){ ?>
<tr>
<td><?php echo $notif['id'] ?></td>
<td><?php echo $notif['data'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Here's controller code
$this->db->limit($this->misc_model->get_notifications_limit(), $offset);
$this->db->where('touserid', get_staff_user_id());
$this->db->order_by('date', 'desc');
$data['notifications'] = $this->db->get(db_prefix() . 'notifications')->result_array();
$this->load->view('admin/sales/sales', $data);
But I don't see the data value get into html table like I want, in table it's show the error message " not_goal_message_failedArray"
I'm trying to encode the json, but I still don't know how to pass the json encode in controller to view in codeigniter
Here's the json encode
$page = $this->input->post('page');
$offset = ($page * $this->misc_model->get_notifications_limit());
$this->db->limit($this->misc_model->get_notifications_limit(), $offset);
$this->db->where('touserid', get_staff_user_id());
$this->db->order_by('date', 'desc');
$notifications = $this->db->get(db_prefix() . 'notifications')->result_array();
$i = 0;
foreach ($notifications as $notification) {
if (($notification['fromcompany'] == null && $notification['fromuserid'] != 0) || ($notification['fromcompany'] == null && $notification['fromclientid'] != 0)) {
if ($notification['fromuserid'] != 0) {
$notifications[$i]['profile_image'] = '<a href="' . admin_url('staff/profile/' . $notification['fromuserid']) . '">' . staff_profile_image($notification['fromuserid'], [
'staff-profile-image-small',
'img-circle',
'pull-left',
]) . '</a>';
} else {
$notifications[$i]['profile_image'] = '<a href="' . admin_url('clients/client/' . $notification['fromclientid']) . '">
<img class="client-profile-image-small img-circle pull-left" src="' . contact_profile_image_url($notification['fromclientid']) . '"></a>';
}
} else {
$notifications[$i]['profile_image'] = '';
$notifications[$i]['full_name'] = '';
}
$data = '';
if (!empty($notification['data'])) {
$data = unserialize($notification['data']);
$x = 0;
foreach ($data as $dt) {
if (strpos($dt, '<lang>') !== false) {
$lang = get_string_between($dt, '<lang>', '</lang>');
$temp = _l($lang);
if (strpos($temp, 'project_status_') !== false) {
$status = get_project_status_by_id(strafter($temp, 'project_status_'));
$temp = $status['name'];
}
$dt[$x] = $temp;
}
$x++;
}
}
$notifications[$i]['description'] = _l($notification['description'], $dt);
$notifications[$i]['date'] = time_ago($notification['date']);
$notifications[$i]['full_date'] = $notification['date'];
$i++;
}
echo json_encode($notifications);
Do you know where's my error when tried convert the json value in the table to html table code ?
Thank you
Your data in your table is looking like a serialised array
You will not get the data via echo, should use
$this->load->view("notification_view", $notifications);
instead of
echo json_encode($notifications);
I want to display checked checkbox which are stored as values in a mysql database.
For now the table stores the value of the checkbox being checked in the database. The header and first column are fetched from three different tables in the database. While the values of the checked check-boxes gets saved in a same table.
Here's the code for inserting the data.
$active = "CourseReport";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
require_once './functions/report-functions.php';
$course = Schema::getCourseReport();
$objective = Schema::getObjective();
$goals = Schema::getGoals();
$mainobj = Schema::getMainObjectives();
$subobj = Schema::getSubObjectives();
?>
<form id="addReport" action ='./functions/report-functions.php' method="post">
<table id="table1" class="table table-hover">
<thead>
<?php
echo '<tr><th>Goals</th>';
for ($i = 0; $i < count($course); $i++) {
echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';
}
echo '</tr>';
?>
</thead>
<tbody>
<?php
for ($y = 0; $y < count($goals); $y++) {
echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>
</tr>';
?>
<?php
for( $z = 0; $z < count($mainobj); $z++){
if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>
</tr>';
?>
<?php
for ($j = 0; $j< count($subobj); $j++) {
if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';
for ($x = 0; $x < count($course); $x++) {
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
}
echo '</tr>';
}
}
}
}
}
?>
</tbody>
</table>
<button class="button" name= "submit" value= "Submit">Submit</button>
</form>
report-functions.php
if( isset( $_POST['submit'], $_POST['check'] ) ){
try{
require_once 'db-connect.php';
$conn = DatabaseConnection::getConnection();
$sql= " insert into `Report` (`ColRow`) values (:value) ";
$stmt = $conn->prepare( $sql );
if( $stmt ){
$conn->beginTransaction();
foreach( $_POST['check'] as $index => $value ) {
$result = $stmt->execute( [ ':value' => $value ] );
if( !$result ) {
echo '
<script>
alert("Error, please try submitting again. Error code 1");
window.history.back();
</script>';
}
}
$conn->commit();
echo '<script>
alert("Report was submitted successfully.");
window.location = ".../";
</script>';
}
} catch( Exception $e ){
$conn->rollback();
exit( $e->getMessage() );
}
I expect that once I submit the table, the table should load the same table with the checked checkboxes. I should be able to make the changes and submit the table over and over again.
Please comment if I need to provide any additional information.
When you display your page (in your first section of code), at some point you do this:
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
The value is set to:
value=c"c.$course[$x]->courseId."-o".$subobj[$j]['SubObjId']";
This value is where you get the checked or not value you mentioned in the comments (like c1-o1.1).
Right. So before you do that echo, add a new if condition.
$value = "c$course[$x]->courseId" . "-o$subobj[$j]['SubObjId']";
if (verify_checked($value)) {
$checked_code = "checked=\"checked\"";
}
else {
$checked_code = "";
}
echo "<td><input name='check[]' type=checkbox value=$value id=checked $checked_code ></td>";
The verify_checked(value) function does (from what I understand of your database, you keep the "grid location" of checked elements):
function verify_checked($value)
{
// Connect to the database if needed
// Perform: SELECT count($value) FROM Report
// If the result is >0, return TRUE
// Else return FALSE
}
The idea here is to query the database every time your are about to echo the <input> element.
Note for concatenating text, I find it more legible to put spaces around the . to clearly split what is part of the text and what is the concatenation dot.
As mentioned previously, indentation is critical for understanding of the different contexts. Until I indented your code, I had not realized how the different loops worked in relation to the others.
I try to display every each data on the specific td, but I dont know where to fix my code. Please check the screenshop below to understand the clearly problems. Please any help to solve this problems.
<table class="table table-hover table-bordered ">
<tr><th>Day</th><th colspan="2">08:00-08:40</th><th colspan="2">8:40-09:20</th><th colspan="2">09:20-10:00</th><th>10:00-10:15</th><th colspan="2">10:15-10:55</th><th colspan="2">10:55-11:35</th><th colspan="2">11:35-12:15</th><th>12:15-01:15</th><th colspan="2">01:15-01:55</th><th colspan="2">01:55-02:35</th></tr>
<?php
$timesVariants = array("08:00-08:40", "08:40-09:20", "09:20-10:00", "10:00-10:15", "10:15-10:55", "10:55-11:35", "11:35-12:15", "12:15-01:15", "01:15-01:55","01:55-02:35");
$sqlquery = "SELECT * FROM timetable,classroom,subprogramme WHERE classroom.classid = timetable.classid AND subprogramme.subid = timetable.subid";
$res = $connect->query($sqlquery);
$classes = array();
while($row = $res->fetch_assoc()) {
$classes[$row['day']][$row['tid']][$row['time']] = array('courseid'=> $row['cid'], 'classname' => $row['classname'], 'subname' => $row['subname']);
}
//This is a loop
foreach($classes as $day => $daySchedule) {
foreach($daySchedule as $teacher) {
print '<tr>';
print "<td>$day</td>";
foreach($timesVariants as $time) {
if (empty($teacher[$time])){
print "<td>*</td><td>*</td>";
}
else{
print '<td>' . $teacher[$time]['courseid'] . '</td><td>' . $teacher[$time]['subname'] . ''. $teacher[$time]['classname'] . '</td>';
}
}
print '</tr>';
}
}
?>
</table>
Output
Results display on the webpage
You trouble is in the GROUP BY. MySql have no strict restrictions (by default) that each column should use aggregation function, so the result is the first row, instead of complicating SQL use PHP, your result seems not to be huge, so another loop will not affect performance:
$timesVariants = array("08:00-08:40", "08:40-09:20", "09:20-10:00", "10:00-10:15", "10:15-10:55", "10:55-11:35", "11:35-12:15", "12:15-1:15", "01:15-01:55","01:55-02:35");
$sqlquery = "SELECT * FROM timetable";
$classes = array();
while($row = $res->fetch_assoc()) {
$classes[$row['day']][$row['tid']][$row['time']] = array('subject'=> $row['subject'], 'class' => $row['class'], 'progid' => $row['progid']);
}
//This is a loop
foreach($classes as $day => $daySchedule) {
foreach($daySchedule as $teacher) {
print '<tr>';
print "<td>$day</td>";
foreach($timesVariants as $time) {
if (empty($teacher[$time]))
print "<td>None</td><td>None</td>";
else
print '<td>' . $teacher[$time]['subject'] . '</td><td>' . $teacher[$time]['class'] . '</td>';
}
print '</tr>';
}
}
<?php
if(isset($_POST["tid"])){
$tid = $connect->real_escape_string($_POST["tid"]);
$sqlquery = "SELECT * FROM timetable,classroom,subprogramme WHERE classroom.classid = timetable.classid AND subprogramme.subid = timetable.subid AND timetable.tid = ".$tid." ORDER BY timetable.timid ASC";
$res = $connect->query($sqlquery);
if($res->num_rows > 0){
?>
<table class="table table-bordered table-striped">
<tr><th>Day</th><th colspan="2">8:00-8:40</th><th colspan="2">8:40-9:20</th><th colspan="2">9:20-10:00</th><th colspan="2">10:00-10:15</th><th colspan="2">10:15-10:55</th><th colspan="2">10:55-11:35</th><th colspan="2">11:35-12:15</th><th colspan="2">12:15-1:15</th><th colspan="2">1:15-1:55</th><th colspan="2">1:55-2:35</th></tr>
<?php
$timesVariants = array("8:00-8:40", "8:40-9:20", "9:20-10:00", "10:00-10:15", "10:15-10:55", "10:55-11:35", "11:35-12:15", "12:15-01:15", "1:15-1:55","1:55-2:35");
$classes = array();
while($row = $res->fetch_assoc()) {
$classes[$row['day']][$row['tid']][$row['time']] = array('courseid'=> $row['cid'], 'classname' => $row['classname'], 'subname' => $row['subname']);
}
//This is a loop
foreach($classes as $day => $daySchedule) {
foreach($daySchedule as $teacher) {
print '<tr>';
print "<td>$day</td>";
foreach($timesVariants as $time) {
if (empty($teacher[$time])){
print "<td>*</td><td>*</td>";
}
else{
print '<td>' . $teacher[$time]['courseid'] . '</td><td>' . $teacher[$time]['subname'] . ''. $teacher[$time]['classname'] . '</td>';
}
}
print '</tr>';
}
}
?>
</table>
<?php
}
else{ print "<div class='alert alert-danger col-md-4'><span class='glyphicon glyphicon-remove'></span> Not yet set timetable</div>"; }
} ?>
</div>
The problems was on td I forgot to put colspan = 2, and other problem on sql query I forgot to inner join the tables in order to get all right that i want to display on the page.
I have a question. How do I do to rescue the variable $row in this function ListarGeral(). so I can use the function EditarGeral() . I tried to do, but nothing happened
here's what I tried to do:
<?php
include ('Banco.php');
Class GeralControle {
private $consulta;
private $row = array();
public function GeraloDao() {
$novaconexao = new Banco();
$this->consulta = $novaconexao->conectar();
}
public function ListarGeral() {
$this->GeraloDao();
echo '<table border="1" cellspacing="2">
<tr>
<td>ID</td>
<td>CPF</td>
</tr>';
if ($resultado = $this->consulta->query("select * from cadastro")) {
while ($this->row = $resultado->fetch_row()) {
echo '<tr>
<td>'.$this->row[0].'</td>
<td>'.$this->row[1].'</td>
</tr>';
echo $this->row[0];
}
$resultado->close();
}
echo '</table>';
}
public function EditarGeral(){
$this->ListarGeral();
echo $this->row[0];
}
}
$pessoa2 = new GeralControle();
$pessoa2->ListarGeral();
$pessoa3 = new GeralControle();
$pessoa3->EditarGeral();
Thank you!
if ($resultado = $this->consulta->query("select * from cadastro")) {
$rows = array();
while ($this->row = $resultado->fetch_row()) {
echo '<tr>
<td>'.$this->row[0].'</td>
<td>'.$this->row[1].'</td>
</tr>
';echo $this->row[0];
array_push($rows, $this->row);
}
EditarGeral($rows);
}
I have an issue with my script somewhere but do not know exactly where it is incorrect. Here is the code:
<title>Log</title>
</head>
<h1> Log </h1>
<form method="get" action="getlog.php">
<table width="300" border="0">
<tr>
<td> Forte ID:</td>
<td><select id="ForteID" name="ForteID">
<option value="nc4682">nc4682</option>
<option value="bs1441">bs1441</option>
<option value="sp3212">sp3212</option>
</select></td>
</tr>
</table>
<input type="submit" name="getLog" value="Get Log">
</form>
</head>
<body>
</body>
</html>
<?php
/*print_r($_POST);*/
$serverName = 'SRB-Nick_Desktop\SQLEXPRESS';
$connectionInfo = array('Database'=>'cslogs', 'UID'=>'cslogslogin', 'PWD'=>'123456');
$connection = sqlsrv_connect($serverName, $connectionInfo);
$query = 'SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes from logs';
$result = sqlsrv_query($connection,$query);
if (!$result)
{
$message = 'ERROR: ' . sqlsrv_errors();
return $message;
}
else
{
$i = 0;
echo '<html><body><table><tr>';
while ($i < sqlsrv_num_rows($result))
{
$meta = sqlsrv_fetch($result, $i);
echo '<td>' . $meta->name . '</td>';
$i = $i + 1;
}
echo '</tr>';
while ( ($row = sqlsrv_fetch_array($result)))
{
$count = count($row);
$y = 0;
echo '<tr>';
while ($y < $count)
{
$c_row = current($row);
echo '<td>' . $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo '</tr>';
}
sqlsrv_free_stmt ($result);
echo '</table></body></html>';
}
sqlsrv_close( $connection);
?>
And this is what I get in result, no matter what is selected in the drop down box and hit the button get log.
nc4682 nc4682 Save Save asdf asdf fdas fdas 1 1 cc cc asdf asdf
bs1441 bs1441 LOC LOC AN00336862 AN00336862 None None 0 0 ach ach Backout Backout
nc4682 nc4682 Save Save AN00336862 AN00336862 easdf easdf 2 2 ach ach asdf asdf
sp3212 sp3212 Sale Sale NCXXXXXX1 NCXXXXXX1 none none 1 1 cc cc asdfasdfasdf asdfasdfasdf
Each column is duplicated. There are supposed to be 7 columns.
To only show the results from the drop down list you would append something like
WHERE ForteID = {$_GET['ForteID']}
to the end of your SQL statement.
sqlsrv_fetch_array() returns both a numeric array and an associative array by default.
Try specifying only one type of array
while ( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC ))
To use your dropdpwn in the query.
$query = 'SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes FROM logs WHERE ForteID =' . $_GET['ForteID'];
Please be aware that without sanitizing the $_GET variable this query is vulnerable to sql injection.