index of fetch array - php

i want to get the index of td that the user clicked , i have an html table fill from database using php ...
this is my index.php :
<html>
<head>
<title>Last 10 Results</title>
</head>
<body>
<table>
<thead>
</thead>
<tbody>
<tr>
<?php
session_start();
$connect = mysqli_connect("localhost","root","","test");
if (!$connect) {
die(mysql_error());
}
$results = mysqli_query($connect,"SELECT * FROM family where parent_id = 0");
while($row = mysqli_fetch_assoc($results)) {
?>
<td onclick="window.location='index2.php'"
<?php $id = $row['id'];
$_SESSION['varname'] = $id;?>>
<?php echo $row['name']?> <br/>
<?php echo $row['description']?> <br/>
<?php echo $row['parent_id']?> <br/>
</td>
<?php
}
?>
</tr>
</tbody>
</table>
</body>
</html>
this is my index2.php :
<html>
<head>
<title>Last 10 Results</title>
</head>
<body>
<table>
<thead>
</thead>
<tbody>
<tr>
<?php
session_start();
$gg = $_SESSION['varname'];
echo $gg;
$connect = mysqli_connect("localhost","root", "","test");
if (!$connect) {
die(mysql_error());
}
$results = mysqli_query($connect,"SELECT * FROM family where parent_id = '$gg' ");
while($row = mysqli_fetch_array($results)) {
?>
<td>
<?php echo $row['id']?> <br/>
<?php echo $row['name']?> <br/>
<?php echo $row['description']?> <br/>
<?php echo $row['parent_id']?> <br/>
</td>
<?php
}
?>
</tr>
</tbody>
</table>
</body>
</html>
now i want to take the "id" of the td that the user click on,, but this code always give me the last id in my database ...
what can i do ?

Replace in Index.php:
<td onclick="window.location='index2.php'"
With:
<td onclick="window.location='index2.php?parent_id=<?php echo $row['id']; ?>'"
And in
Index2.php:
$gg = $_SESSION['varname'];
With:
$gg = (int)$_GET['parent_id'];
It's better to use $_GET variable for this than $_session (urls are search engine friendly)

Related

update.php file in not working properly. and error is not showing

i create a curd apllication with the help of php and mysql there is work all operation insert, read and delete but in update option it not work. when i click on update button it is jump directly on display.php page.
this is my display.php code
<?php
include 'conc.php';
// $username = $_POST["username"];
// $password = $_POST["password"];
$q = "select * from cued_data";
$query = mysqli_query($con , $q);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>display data</title>
<link rel="stylesheet" href="curd.css">
</head>
<body>
<div class="container">
<h1>display Table Data</h1>
<table class="table">
<tr>
<th>Id</th>
<th>Username</th>
<th>Password</th>
<th>Delete</th>
<th>Update</th>
</tr>
<?php
include 'conc.php';
$q = "select * from cued_data";
$query = mysqli_query($con , $q);
while($res = mysqli_fetch_array($query)){
?>
<tr>
<td> <?php echo $res['id']; ?> </td>
<td> <?php echo $res['name']; ?> </td>
<td> <?php echo $res['password']; ?> </td>
<td><button class="dlt"> <a href="delete.php?id= <?php echo $res['id']; ?>" > Delete: </a> </button> </td>
<td><button class="dlt"> <a href="update.html?id= <?php echo $res['id']; ?>" > Update: </a> </button> </td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
this is my update.php file
<?php
include "conc.php";
include "display.php";
$id = $_GET["id"]; # i think error in this section
$username = $_POST["name"];
$password = $_POST["password"];
// $q = "delete from `cued_data` where id = $id" ;
$msql= " update cued_data set id ='$id', name = '$username', password = '$password' where id = '$id' ";
$query = mysqli_query($con, $msql);
header("location:display.php");
?>
this is my delete.php file
<?php
include "conc.php";
$id = $_GET["id"];
$q = "delete from `cued_data` where id = $id" ;
$query = mysqli_query($con, $q);
header("location:display.php");
?>

PHP if else question regarding simple to do list

To do list:
I have created the HTML and php code to insert data into the database, and read from it.
Database is looking like this:
task_id |task_desc |task_target |task_finished_date |task_status
40 |test p |2020-07-25 |2020-07-23 |completed
Task_target and task_finished_date are using type date in the database.
task_target is getting value on creation of the task, and task_finished_date is getting automatically value when we mark the job completed using now():
$task_id = $_GET['completed'];
mysqli_query($db, "UPDATE tasks SET task_status = 'completed' WHERE task_id=". $task_id);
mysqli_query($db, "UPDATE tasks SET task_finished_date = now() WHERE task_id=". $task_id);
mysqli_query($db, "ORDER BY task_finished_date DESC ". $task_id);
header("Location: index.php" );
}
I am currently trying to program it when some task is completed AFTER the deadline to be displayed in "Failed" table, and if is closed before the deadline to be displayed in completed table.
<tbody>
<?php $i = 1; while ($row = mysqli_fetch_array($finished_tasks)) { ?>
<tr>
<?php
if($targetd > $finished_d){ ?>
<td class="successful"> <?php echo $i; ?> </td>
<td class="successful"> <?php echo $row['task_desc']; ?> </td>
<td class="successful"> <?php echo $row['task_finished_date']; ?> </td>
<?php }?>
</tr>
<?php $i++; } ?>
</tbody>
<thead>
<tr>
<th>N</th>
<th>Failed Tasks</th>
<th style="width: 197px;">Task finished time</th>
</tr>
</thead>
<tbody>
<?php $i = 1; while ($row = mysqli_fetch_array($finished_tasks)) { ?>
<tr>
<?php
if($targetd < $finished_d){ ?>
<td class="failed"> <?php echo $i; ?> </td>
<td class="failed"> <?php echo $row['task_desc']; ?> </td>
<td class="failed"> <?php echo $row['task_finished_date']; ?> </td>
<?php }?>
</tr>
<?php $i++; } ?>
</tbody>
As in the $finished_tasks variable i have storing the values for the completed tasks:
$finished_tasks = mysqli_query($db, "SELECT * FROM tasks WHERE task_status = 'completed' ");
$finished_task_time = mysqli_query($db, "SELECT task_finished_date FROM tasks WHERE task_status = 'completed' ");
$planned_target_time = mysqli_query($db, "SELECT task_target FROM tasks WHERE task_status = 'completed' ");
while ($row = mysqli_fetch_array($finished_tasks)) {
$targetd = $row['task_target'];
$finished_d = $row['task_finished_date'];
Have tried to get the deadline(task_target)and target(task_finished_date) and insert them in both variables and then compare them, and based on this comparison to display them where I want, but the logic here is not right I think.
How I can separate the tasks based on the desired condition?
Entire Code Below:
<?php
// initialize errors variable
$errors = "";
// connect to database
$db = mysqli_connect("localhost", "root", "", "todo");
// insert a quote if submit button is clicked
if (isset($_POST['submit'])) {
if (empty($_POST['task_desc'])) {
$errors = "You must fill in the task";
}else{
$task_desc = $_POST['task_desc'];
$task_target = $_POST['task_target'];
$sql = "INSERT INTO tasks (task_desc, task_target) VALUES ('$task_desc', '$task_target')";
mysqli_query($db, $sql);
header('location: index.php');
}
}
// delete task
if (isset($_GET['del_task'])) {
$task_id = $_GET['del_task'];
mysqli_query($db, "DELETE FROM tasks WHERE task_id=".$task_id);
header('location: index.php');
}
if(isset($_GET['completed'])){
$task_id = $_GET['completed'];
mysqli_query($db, "UPDATE tasks SET task_status = 'completed' WHERE task_id=". $task_id);
mysqli_query($db, "UPDATE tasks SET task_finished_date = now() WHERE task_id=". $task_id);
mysqli_query($db, "ORDER BY task_finished_date DESC ". $task_id);
header("Location: index.php" );
}
// select all tasks if page is visited or refreshed
$tasks = mysqli_query($db, "SELECT * FROM tasks WHERE task_status = 'Active' ");
?>
<!DOCTYPE html>
<html>
<head>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title>ToDo List Application PHP and MySQL</title>
</head>
<body>
<!-- Page Content -->
<div class="container">
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-12">
<div class="heading">
<h2 style="font-style: 'Hervetica';">ToDo List Application PHP and MySQL database</h2>
</div>
<form method="post" action="index.php" class="input_form">
<?php if (isset($errors)) { ?>
<p><?php echo $errors; ?></p>
<?php } ?>
<label for="task_target">Select Date:</label>
<input type="date" class="form-control" name="task_target">
<label for="task_desc">Describe your task:</label>
<textarea class="form-control" name="task_desc" id="body" cols="30" rows="5"></textarea>
<button type="submit" name="submit" id="add_btn" class="form-control">Add Task</button>
</form>
<table class="table table-bordered">
<thead>
<tr>
<th>N</th>
<th>Ongoing Tasks</th>
<th>Target Date</th>
<th>Action</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php $i = 1; while ($row = mysqli_fetch_array($tasks)) { ?>
<tr>
<td> <?php echo $i; ?> </td>
<td> <?php echo $row['task_desc']; ?> </td>
<td> <?php echo $row['task_target']; ?> </td>
<td>
Delete
</td>
<td>
Complete
</td>
</tr>
<?php $i++; } ?>
</tbody>
</table>
<?php
$finished_tasks = mysqli_query($db, "SELECT * FROM tasks WHERE task_status = 'completed' ");
$finished_task_time = mysqli_query($db, "SELECT task_finished_date FROM tasks WHERE task_status = 'completed' ");
$planned_target_time = mysqli_query($db, "SELECT task_target FROM tasks WHERE task_status = 'completed' ");
while ($row = mysqli_fetch_array($finished_tasks)) {
$targetd = $row['task_target'];
$finished_d = $row['task_finished_date'];
?>
<table class="table table-bordered">
<thead>
<tr>
<th>N</th>
<th>Successful Tasks</th>
<th style="width: 197px;">Task finished time</th>
</tr>
</thead>
<tbody>
<?php $i = 1; while ($row = mysqli_fetch_array($finished_tasks)) { ?>
<tr>
<?php
if($targetd > $finished_d){ ?>
<td class="successful"> <?php echo $i; ?> </td>
<td class="successful"> <?php echo $row['task_desc']; ?> </td>
<td class="successful"> <?php echo $row['task_finished_date']; ?> </td>
<?php }?>
</tr>
<?php $i++; } ?>
</tbody>
</table>
<table class="table table-bordered">
<thead>
<tr>
<th>N</th>
<th>Failed Tasks</th>
<th style="width: 197px;">Task finished time</th>
</tr>
</thead>
<tbody>
<?php $i = 1; while ($row = mysqli_fetch_array($finished_tasks)) { ?>
<tr>
<?php
if($targetd > $finished_d){ ?>
<td class="failed"> <?php echo $i; ?> </td>
<td class="failed"> <?php echo $row['task_desc']; ?> </td>
<td class="failed"> <?php echo $row['task_finished_date']; ?> </td>
<?php }?>
</tr>
<?php $i++; } ?>
</tbody>
</table>
<?php } ?>
</div>
</div>
</div>
</body>
</html>
Your question is quite ambiguous, what kind of error or unexpected output are you getting?
Had to strip your code of the HTML part and the PHP part not affecting the logic, here's what I have.
$finished_tasks = mysqli_query($db, "SELECT * FROM tasks WHERE task_status = 'completed' ");
$finished_task_time = mysqli_query($db, "SELECT task_finished_date FROM tasks WHERE task_status = 'completed' ");
$planned_target_time = mysqli_query($db, "SELECT task_target FROM tasks WHERE task_status = 'completed' ");
while ($row = mysqli_fetch_array($finished_tasks)) {
$targetd = $row['task_target'];
$finished_d = $row['task_finished_date'];
$i = 1;
while ($row = mysqli_fetch_array($finished_tasks))
{
if($targetd > $finished_d)
{
echo $i;
echo $row['task_desc'];
echo $row['task_finished_date'];
$i++;
}
$i = 1;
while ($row = mysqli_fetch_array($finished_tasks))
{
if($targetd > $finished_d)
{
echo $i;
echo $row['task_desc'];
echo $row['task_finished_date'];
}
$i++;
}
}
All three while loops assign a value to the $row variable. This would cause some unexpected results as some values may be skipped.
You're referencing the SQL result indexes inappropriately.
I have managed to find a easy fix of my question.
First of all thanks to all who tried to help me and advised way of effective learning.
Really like this place.
So, on the answer:
As in the begging i have described that the Deadline of the task is defining during the creation of the task, and the closing time is getting to the database when the user click Completed button.
So i have decided to have the sort directly into the database modifying the queries like this:
$finished_tasks = mysqli_query($db, "SELECT * FROM tasks WHERE task_status = 'completed' AND task_finished_date < task_target ");
$finished_failed_tasks = mysqli_query($db, "SELECT * FROM tasks WHERE task_status = 'completed' AND task_finished_date > task_target ");
In this way i have all of the completed successfully tasks in $finished_tasks variable and all of the failed in $finished_failed_tasks, after that the displaying in the page is easy.
I am not quite sure if this is practical solution, but in this way working as i desired.
Next step is to strip and refactor the code as you suggested.
Once again, thanks really much and have a nice day.
Regards, Kristiyan

I am trying to add a dropdown menu box within a table with data fetched from mysql

I am using notepad, xampp and mysql and phpMyadmin to create a football prediction website. On the prediction page I have a page showing the fixture in a table. I want the use to be able to post a Home_Sore and Away_Score for each corresponding fixture using a series of dropdown menus with numbers 1-20.
For example:
Fixture_ID|Home_Team|Home_Score|Away_Score|Away_Team|
1 Man United <Dropdown> <Dropdown> Spurs
Is this possible? I am new to php coding and would appreciate any help i get!:)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<?php
$connection = mysql_connect('localhost', 'root', 'password'); //The Blank string is the password
mysql_select_db('mls');
$query = "SELECT * FROM fixtures"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
$columns = array();
$resultset = array();
# Set columns and results array
while ($row = mysql_fetch_assoc($result)) {
if (empty($columns)) {
$columns = array_keys($row);
}
$resultset[] = $row;
}
# If records found
if( count($resultset > 0 )) {
?>
<table class="table table-bordered" >
<thead>
<tr class='info';>
<?php foreach ($columns as $k => $column_name ) : ?>
<th> <?php echo $column_name;?> </th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php
// output data of each row
foreach($resultset as $index => $row) {
$column_counter =0;
?>
<tr class='success';>
<?php for ($i=0; $i < count($columns); $i++):?>
<td> <?php echo $row[$columns[$column_counter++]]; ?> </td>
<?php endfor;?>
</tr>
<?php } ?>
</tbody>
</table>
<?php }else{
?>
<h4> echo Information Not Available </h4>
<?php }
?>
</body>
</html>
You can do this by including something like this in td tag
<select name="mySelect">
<?php $result= mysql_query('SELECT * FROM fixtures'); ?>
<?php while($row= mysql_fetch_assoc($result)) { ?>
<option value="<?php echo $row['your_column_name'];?>">
<?php echo $row['your_column_name']; ?>
</option>
<?php } ?>
</select>

HTML Table with inline PHP

I want to create a HTML Table, but the rows should be generated from the values from a mysql database. The problem is that I want to have a boolean box where the user can mark it, and then press a button to update the table in the database. How do I do such a thing ?
Code so far:
<?php
session_start();
require("connectToEvent_log.php");
$connectToEvent = connect2db();
$uid = '2'; // for the filnal version: #$_SESSION['uid'];
$view_event = "SELECT * FROM event_log WHERE uid = $uid";
$view_event_query = mysqli_query($connectToEvent, $view_event);
$row = mysqli_num_rows($view_event_query);
$print = mysqli_fetch_array($view_event_query);
?>
<html>
<head>
<title>Events</title>
</head>
<body>
<form action="viewEvents.php" method="POST">
<table border = '1'>
<tr>
<?php
while($row != 0){
echo "<td>".$print['hours']."</td>";
echo "<td>".$print['date']."</td>";
}
?>
</tr>
</table>
<form/>
</form>
</body>
</html>
You can easily iterate over the result from the mysqli_fetch_array function to create the table rows. Creating a checkbox markup is done easily, i assume that the table has a primary key id and the column, that stores the checkbox value (0 or 1) is called checkbox.
<?php
session_start();
require("connectToEvent_log.php");
$connectToEvent = connect2db();
$uid = '2'; // for the filnal version: #$_SESSION['uid'];
$view_event = "SELECT * FROM event_log WHERE uid = $uid";
$view_event_query = mysqli_query($connectToEvent, $view_event);
$num_rows = mysqli_num_rows($view_event_query);
$rows = mysqli_fetch_array($view_event_query);
?>
<html>
<head>
<title>Events</title>
</head>
<body>
<form action="viewEvents.php" method="POST">
<table border="1">
<thead>
<tr>
<td>Id</td>
<td>Date</td>
<td>Hours</td>
<td>Checkbox</td>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < count($num_rows); $i++) {
?>
<tr>
<td><?php print $rows[$i]["eid"]; ?></td>
<td><?php print $rows[$i]["date"]; ?></td>
<td><?php print $rows[$i]["hours"]; ?></td>
<td><input type="checkbox" name="row[<?php $rows[$i]["eid"]?>][checkbox]" value="1" <?php if ($rows[$i]["accepted"]) print ' checked="checked"'; ?>/></td>
</tr>
<?php
}
?>
</tbody>
</table>
<input type="submit" />
</form>
</body>
</html>

Call to undefined function ProdTotal()

I am trying to call function ProdTotal to get the total quantity order and total amount ordered for a product and load it in the table in the Display Function. I am getting the error: Call to undefined function ProdTotal();
<?php
Class CarsClass {
private $user = 'php06';
private $pwd = 'php06';
private $dbConn;
function __construct($db='classicmodels') {
//Create connection to MySQL database requested, if blank just connect up.
$this->dbConn = new mysqli('localhost', $this->user, $this->pwd, $db);
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "select count(*) as 'custcount' from customers";
$result = $this->dbConn->query($query);
$row = $result->fetch_assoc();
$custCount = $row['custcount'];
print "Connected to DB $db as user $this->user<br><br> Number of Rows $custCount<br><br>";
}
function __destruct(){
mysqli_close();
Print "DB closed by user <br><br>";
}
function header(){
echo "Midterm Exam Script 2 Header<br><br>";
}
function display(){
$totqty = 0;
$totamt = 0;
//get row from WB_Resident Table
$query = "select productCode,productName,productDescription,quantityInStock,buyprice,MSRP from products";
$result = $this->dbConn->query($query);
?>
<table id="midterm2">
<tr>
<th colspan="13">Product Database Table</th>
</tr>
<tr>
<th width="2%">productCode</th>
<th width="10%">productName</th>
<th width="10%">productDescription</th>
<th width="10%">quantity in stock</th>
<th width="10%">buyPrice</th>
<th width="2%">MSRP</th>
<th width="10%">Total Qty Ordered</th>
<th width="10%">Total $ Ordered</th>
</tr>
<?php
while($row = $result->fetch_assoc()):
$producta = $row["productCode"];
ProdTotal($producta);
?>
<tr>
<td>
<?php echo $row["productCode"]; ?>
</td>
<td>
<?php echo $row["productName"];?>
</td>
<td>
<?php echo $row["productDescription"]; ?>
</td>
<td>
<?php echo $row["Qty In Stock"]; ?>
</td>
<td>
<?php echo $row["Buy Price"]; ?>
</td>
<td>
<?php echo $row["MSRP"]; ?>
</td>
<td>
<?php echo $totqty; ?>
</td>
<td>
<?php echo $totamt; ?>
</td>
</tr>
<?php
endwhile;
?>
</table>
<?php
}
function footer(){
echo "Midterm Exam Script 3 Footer<br><br>";
}
function ProdTotal($product){
echo "product code entered = $product <br><br>";
$query = "select RTRIM(productCode) as productt, quantityOrdered, priceEach from orderdetails order by productt";
$result = $this->dbConn->query($query);
while($row = $result->fetch_assoc()){
if ($row["productt"] == $product){
echo $row;
$total = $row["quantityOrdered"] * $row["priceEach"];
$totqty = $totqty + $row["quantityOrdered"];
$totamt = $totamt + $total;
echo totqty;
echo totamt;
return array($totqty, $totamt);
}
}
}
}
?>
This script is executed to call class.
<html>
<head>
<title>Midterm2 Script 3</title>
<link rel="stylesheet" type="text/css" href="midterm2.css" />
</head>
<body>
<?php
require 'CarsClass3a.php';
$obj1= new CarsClass('classicmodels');
$obj1->header();
$obj1->display();
$obj1->footer();
?>
</body>
</html>
In display(), change the call to ProdTotal() to
list($totqty, $totamt) = $this->ProdTotal($producta);

Categories