Updating and deleting in a same html form - php

I have added update and delete button in the same form using following codes. Deletion is working perfectly. But updating is again not taking the value of "id".
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dp = "tool";
$dp= new mysqli($servername, $username, $password, $dp) or die("Unable to connect");
//echo"Great work";
?>
<!DOCTYPE html>
<html>
<head>
<title>registration</title>
<meta charset="UTF-8">
<link href="site.css" rel="stylesheet">
<div align="center">
<link rel="stylesheet" href="mine.css"/>
<table border="0" align="center" style="border-spacing: 40px 20px;">
<align="center"> <td>
</head>
<body bgcolor=" #b3ffe0">
<style>
html {
font-family: "Lucida Sans", sans-serif;
}
ul li {display: block;position: relative;float: left;border:1px }
ul li a {display: block;text-decoration: none; white-space: nowrap;color: #fff;}
ul {
list-style-type: none;
padding: 2px ;
margin-left: auto;
background-color: #666;
}
li a, .dropbtn {
display: inline-block;
color: white;
text-align: center;
padding: 10px 20px;
text-decoration: none;
}
li a:hover, .dropdown:hover .dropbtn {
background-color: #111;
}
</style>
</head>
<body>
<form method="post">
<ul>
<li><a class="active" href="df1.php">Disease</a></li>
<li><a href="drug.php" >Drug</a></li>
<li>Interaction</li>
Alternate Drug
</ul>
<?php
$query = "SELECT * FROM disease;";
$result = mysqli_query($dp, $query);
echo "<table border=5>
<tr>
<th>Disease ID</th>
<th>Disease</th>
<th>Sub Disease</th>
<th>Associated Disease</th>
<th>Ethinicity</th>
<th>Source</th>
<th>Edit</th>
</tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row{'id'}."</td>";
echo "<td>".$row{'Disease'}."</td>";
echo "<td>".$row{'SubDisease'}."</td>";
echo "<td>".$row{'Associated_Disease'}."</td>";
echo "<td>".$row{'Ethinicity'}."</td>";
echo "<td>".$row{'Source'}."</td>";
echo "<td><input type='radio' name='id' value='".$row[id]."'></td>";
echo "</tr>";}
echo "</table>";
// $selectedRow=$_POST['id'];
?>
<div>
<table border="0" align="center" style="border-spacing: 40px 30px;">
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="4" WIDTH="40%">
</br><center>
<button style="color: red">Add</button>
<input type = 'submit' value = 'Update' name = 'submitupdate'>
<input type = 'submit' value = 'Delete' name = 'submitdelete'>
</center></TABLE>
<?php
if(isset($_POST[submitupdate]))
{
header ("Location: http://localhost/card/edit3.php");
}
if ($_POST[submitdelete])
{
$conn = mysqli_connect('localhost','root','','tool');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_error());
}
//
$sql="DELETE FROM disease WHERE id=".$_POST['id'];
echo "Data deleted successfully";
mysqli_query($conn, $sql);
mysqli_close($conn);
}
?>
</body>
</html>
Edit3.php
<?php
$conn = mysqli_connect('localhost','root','','tool');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_error());
}
$query = "SELECT * FROM disease where id=".$_POST['id'];
$result = mysqli_query($conn, $query);
$count= mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
echo $count;
?>
<form action="update.php" method="post">
<input type="hidden" value="<?php echo $row['id'];?>" name="id"/>
Disease (ICD10) <select id= "Disease" name="Disease">
<option value="Certain infectious and parasitic diseases">Certain infectious and parasitic diseases</option>
<option value="Neoplasms">Neoplasms</option>
<option value="Diseases of the blood and blood-forming organs and certain disorders involving the immune mechanism ">Diseases of the blood and blood-forming organs and certain disorders involving the immune mechanism</option>
SubDisease<input type="text" name="SubDisease" value="<?php echo $row['SubDisease'];?>"/>
Associated Disease<input type="text" name="Associated_Disease" value="<?php echo $row['Associated_Disease'];?>"/>
<td>Ethinicity<input type="text" list="Ethinicity" id="color" name="Ethinicity" value="<?php echo $row['Ethinicity'];?>" style="width:100px;">
<datalist id="Ethinicity">
<option value="Indian">
<option value="American">
<option value="Srilankan">
</datalist>
</td>
Source<input type="text" name="Source" value="<?php echo $row['Source'];?>"/>
<input type="submit" value="update">
</form>
update.php
<?php
$conn = mysqli_connect('localhost','root','','tool');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_error());
}
$disease = $_POST['Disease'];
$SubDisease = $_POST['SubDisease'];
$Associated_Disease = $_POST['Associated_Disease'];
$Ethinicity = $_POST['Ethinicity'];
$Source = $_POST ['Source'];
$id = $_POST ['id'];
$update= "Update disease set Disease='".$disease."', SubDisease='".$SubDisease."', Associated_Disease='".$Associated_Disease."', Ethinicity='".$Ethinicity."', Source='".$Source."' where id=".$_POST["id"];
if(!mysqli_query($conn,$update))
echo mysqli_error;
?>
And drop down of Disease, is also not getting reading the databse value and not getting display in the editing page.

Related

How to export data from my database and import it in CSV file in the correct format

I'm trying to search for some data then download it as CSV file, but when I click download button to download the data I have found, it's writing all my HTML code at the beginning of the file then it writes my data in the downloaded file. So how can I get only my data without writing the html code with it?.
Code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "CNG492";
$message = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<html>
<head>
<title>Search By Keyword</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Upload Data Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<style>
table {
font-family: Raleway;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
body
{
background-color: #722f37;
}
.btn{
background-color: #722f37;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
.box
{
background-color: #ffffff;
margin: 100px auto;
font-family: Raleway;
padding: 40px;
width: 80%;
min-width: 300px;
}
.has-error
{
border-color:#cc0000;
background-color:#ffff99;
}
.form{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}
</style>
</head>
<body>
<div class="container box">
<br />
<h1 align="center">Search</h1><br />
<form method="post" id="search_form">
<div class="form-group">
<label>Keyword:</label>
<input type="text" name="keyword" id="keyword" class="form-control"/>
<span id="error_keyword" class="text-danger"></span>
</div>
<div align="inline">
<button type="button" name="find_keyword" id="find_keyword" class="btn btn-dark btn-lg">Find</button>
<button type="button" name="adv_search" id="adv_search" class="btn btn-dark btn-lg">Advance Search</button>
</div>
<br>
<?php
if(isset($_POST["keyword"])){
$keyword = mysqli_real_escape_string($conn,$_POST["keyword"]);
$dataset_result = -1;
//Search for keyword inside tables
$search_query = "SELECT dataset_id,title,description FROM dataset WHERE dataset_id IN (SELECT dataset_id FROM dataset WHERE title LIKE '%{$keyword}%' OR collector LIKE '%{$keyword}%' OR description LIKE '%{$keyword}%' OR d_procedure LIKE '%{$keyword}%'
UNION DISTINCT
SELECT dataset_id FROM group_table WHERE group_desc LIKE '%{$keyword}%'
UNION DISTINCT
SELECT dataset_id FROM material WHERE m_type LIKE '%{$keyword}%' OR URI LIKE '%{$keyword}%'
UNION DISTINCT
SELECT dataset_id FROM task WHERE type LIKE '%{$keyword}%' OR description LIKE '%{$keyword}%'
UNION DISTINCT
SELECT dataset_id FROM dataset WHERE eq_id IN (SELECT e.eq_id FROM tracker t,equipment e WHERE t.tracker_id=e.tracker_id AND (t.brand LIKE '%{$keyword}%' OR t.model LIKE '%{$keyword}%')))";
$search_result = $conn->query($search_query);
$dataset_result = mysqli_num_rows($search_result);
if ($dataset_result == 0) {
echo '
<div class="alert alert-success">
No reasults found.
</div>
';
}else{
echo '
<h4>Results</h4>
<table>
<tr>
<th>Title</th>
<th>Description</th>
<th>Dowload Link</th>
</tr>';
while ($row = mysqli_fetch_assoc($search_result)) {
echo '<tr>
<td>'.$row["title"].'</td>
<td>'.$row["description"].'</td>
<td><button type="submit" name="download" id="download" value="'.$row["dataset_id"].'">Dowload</button></td>
</tr>';
}
echo '</table>
';
if (isset($_POST["download"])) {
$d_id = $_POST["download"];
include 'download.php';
}
}
}
mysqli_close($conn);
?>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$('#find_keyword').click(function(){
var error_keyword = '';
if($.trim($('#keyword').val()).length == 0){
error_keyword = 'Enter a keyword please.'
$('#error_keyword').text(error_keyword);
$('#keyword').addClass('has-error');
}else
{
error_keyword = '';
$('#error_keyword').text(error_keyword);
$('#keyword').removeClass('has-error');
}
if(error_keyword != ''){
return false;
}else{
$('#find_keyword').attr("disabled", "disabled");
$(document).css('cursor', 'prgress');
$("#search_form").submit();
}
});
})
</script>
Download.php
<?php
//include database configuration file
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "CNG492";
$message = "";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//get records from database
$query = $connect->query("SELECT * FROM dataset");
if($query->num_rows > 0){
$delimiter = ",";
$filename = "members_" . date('Y-m-d') . ".csv";
//create a file pointer
$f = fopen('php://memory', 'w');
//set column headers
$fields = array('title', 'description');
fputcsv($f, $fields, $delimiter);
//output each row of the data, format line as csv and write to file pointer
while($row = $query->fetch_assoc()){
$lineData = array($row['title'], $row['description']);
fputcsv($f, $lineData, $delimiter);
}
//move back to beginning of file
fseek($f, 0);
//set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
}
exit;
?>
The whole problem is then that you echo some html and inside it include download.php
echo '
<h4>Results</h4>
<table>
<tr>
<th>Title</th>
<th>Description</th>
<th>Dowload Link</th>
</tr>';
while ($row = mysqli_fetch_assoc($search_result)) {
echo '<tr>
<td>'.$row["title"].'</td>
<td>'.$row["description"].'</td>
<td><button type="submit" name="download" id="download" value="'.$row["dataset_id"].'">Dowload</button></td>
</tr>';
}
echo '</table>
';
if (isset($_POST["download"])) {
$d_id = $_POST["download"];
include 'download.php';
}
just put a link to the download.php instead of including it.
echo '
<h4>Results</h4>
<table>
<tr>
<th>Title</th>
<th>Description</th>
<th>Dowload Link</th>
</tr>';
while ($row = mysqli_fetch_assoc($search_result)) {
echo '<tr>
<td>'.$row["title"].'</td>
<td>'.$row["description"].'</td>
<td><button type="submit" name="download" id="download" value="'.$row["dataset_id"].'">Dowload</button></td>
</tr>';
}
echo '</table>
';
if (isset($_POST["download"])) {
$d_id = $_POST["download"];
echo 'Download File';
}
If you want to redirect user after submitting form to the download.php automatically then you may use attribute action in form.
See how it is done HTML Attribute where a redirection is set to the page /action_page.php.

Connecting tables PHP

I'm a number of days busy with a PHP script.
This is what I want:
- People can type their ZIP code. If their ZIP code is in table1 than do .. if their ZIP code is in table2 than do... If their ZIP code is in none of the tables than ...
- I can insert ZIP code with other data example name.
But I don't know how to build this. I have searched on the internet I have tried to get what I have. But the function to search in other tables en than do that. It don't work for me
This is what I have:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Plusgas - Postcode invoeren</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="bootstrap/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Courgette" rel="stylesheet">
<script src="bootstrap/bootstrap.min.js"></script>
<style>
body{
font-family: Courgette;
}
.submit{
background-color: purple;
color:white;
text-size:24px;
padding: 6px;
border-radius: 5px;
border:1px solid white;
font-size: 24px;
}
.submit:hover{
background-color: white;
color: purple;
box-shadow: 0px 0px 20px white;
}
h1{
font-size: 14px;
}
td,th{
padding: 4px;
text-align: center;
}
</style>
</head>
<?php
$servername = "localhost";
$username="*";
$password="*";
$dbname="*";
$id="";
$postcode="";
$provincie="";
$website="";
$contactpersoon="";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//connect to mysql database
try{
$conn =mysqli_connect($servername,$username,$password,$dbname);
}catch(MySQLi_Sql_Exception $ex){
echo("error in connecting");
}
//get data from the form
function getData()
{
$data = array();
$data[1]=$_POST['postcode'];
$data[2]=$_POST['provincie'];
$data[3]=$_POST['website'];
$data[4]=$_POST['contactpersoon'];
return $data;
}
//search
if(isset($_POST['search']))
{
$info = getData();
$search_query="SELECT * FROM postcodes WHERE id = '$info[0]'";
$search_result=mysqli_query($conn, $search_query);
if($search_result)
{
if(mysqli_num_rows($search_result))
{
while($rows = mysqli_fetch_array($search_result))
{
$id = $rows['id'];
$postcode = $rows['postcode'];
$provincie = $rows['provincie'];
$website = $rows['website'];
$contactpersoon = $rows['contactpersoon'];
}
}else{
echo("no data are available");
}
} else{
echo("result error");
}
}
//insert
if(isset($_POST['insert'])){
$info = getData();
$insert_query="INSERT INTO `postcodes`(`postcode`, `provincie`, `website`, `contactpersoon`) VALUES ('$info[1]','$info[2]','$info[3]','$info[4]')";
try{
$insert_result=mysqli_query($conn, $insert_query);
if($insert_result)
{
if(mysqli_affected_rows($conn)>0){
echo("Postcode is toegevoegd");
}else{
echo("Postcode is niet toegevoegd");
}
}
}catch(Exception $ex){
echo("error inserted".$ex->getMessage());
}
}
?>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-lg-4">
<form method ="post" action="">
<h1>ID nummer (voor filterern)</h1>
<input type="number" name="id" class="form-control" placeholder="ID No. /Automatic Number Genrates" value="<?php echo($id);?>" disabled>
<div class="form-group row">
<div class="col-xs-6">
<h1>Postcode</h1>
<input type="text" name="postcode" class="form-control" placeholder="Postcode" value="<?php echo($postcode);?>" required>
</div>
<div class="col-xs-6">
<h1>Provinicie</h1>
<input type="text" name="provincie" class="form-control" placeholder="Provinicie" value="<?php echo($provincie);?>" required>
</div>
</div>
<h1>Website</h1>
<select name="website" class="form-control" value="<?php echo($website);?>">
<option value="websiteZH">Website Zuid-Holland</option>
<option value="websiteNH">Website Noord-Holland</option>
<option value="websiteZL">Website Zeeland</option>
<option value="websiteUT">Website Utrecht</option>
</select>
</div>
<div class="col-xs-6">
<h1>Contactpersoon</h1>
<input type="text" name="contactpersoon" class="form-control" placeholder="Contactpersoon" value="<?php echo($contactpersoon);?>" required>
</div>
</div>
<div>
<input type="submit" class="btn btn-success btn-block btn-lg" name="insert" value="Add">
</div>
</form>
</div>
<div class="col-lg-8">
<h2>Student Data</h2>
<?php
$servername = "localhost";
$username = "*";
$password = "*";
$dbname = "*";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id,postcode,provincie,website,contactpersoon FROM postcodes";
$result = $conn->query($sql);
echo "<table border='1'>
<tr>
<th>Search ID</th>
<th>Postcode</th>
<th>Provinicie</th>
<th>Website</th>
<th>Contactpersoon</th>
</tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['postcode'] . "</td>";
echo "<td>" . $row['provincie'] . "</td>";
echo "<td>" . $row['website'] . "</td>";
echo "<td>" . $row['contactpersoon'] . "</td>";
echo "</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</div>
</div>
</body>
</html>
I'm not realy sure what you want to achieve, what goes wrong, but for sure i see one problem - your function getData() returns array indexed 1..4. Then you get it in search part and you search for $info[0], and that is never set.
2nd of all - this is dangerous way of coding. If someone mean will use your code, he can use SQL injections. Not to manting, that even by mystake someone can use ' (apostroph) and crash SQL query. You should always escape data passed to queries, ie by using real_escape_string() or prepared statements.

Can someone explain why my MySQL table data is not being displayed?

I'm new to PHP and MySQL. I have an HTML table and form that submits the entered data to MySQL, but doesn't display the MySQL data in my HTML table. Here is an image for reference: https://i.imgur.com/OEDd6Px.png. I want the submitted data to display upon submission if possible but am unable to find a solution. Thanks in advance.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$conn = mysqli_connect($host, $user, $pass, $db);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
if(isset($_POST["asin"]))
{
$asin = $_POST["asin"];
$category = $_POST["category"];
$submit = "INSERT INTO `user_input`(`id`, `asin`, `category`, `date`) VALUES (NULL, '$asin', '$category', CURRENT_DATE())";
$sql = mysqli_query($conn, $submit);
if (!$sql) {
die ('SQL Error: ' . mysqli_error($conn));
}
$display = "SELECT * FROM user_input";
$result = mysqli_query($conn, $display);
if (!$result) {
die ('SQL Error: ' . mysqli_error($conn));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>testEnv</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<style>
form {
padding-bottom: 10px;
padding-top: 10px;
}
table, thead, tbody, th, td {
padding: 4px;
border-collapse: collapse;
border: 1px solid black;
}
form {
font-size: 13px;
}
th, td {
width: auto;
text-align: center;
font-size: 13px;
}
</style>
</head>
<body>
<div class="container-fluid">
<form id="form" method="post">
<div>
<label id="asinLabel" for="asin">ASIN:</label>
<input id="asinInput" type="text" name="asin"></input>
<label id="categoryLabel" for="category">Category:</label>
<input id="categoryInput" type="text" name="category"></input>
<input id="submit" type="submit" value="Submit"></input>
</div>
</form>
</div>
<div class="container-fluid">
<table class="container-fluid">
<thead>
<tr>
<th>ID</th>
<th>ASIN</th>
<th>Category</th>
<th>Date</th>
<th>6:00 AM</th>
<th>8:00 AM</th>
<th>10:00 AM</th>
<th>12:00 PM</th>
</tr>
</thead>
<tbody id="tableBody">
<?php
while($row = mysqli_fetch_array($result));
{
echo '<tr>
<td>'.$row['id'].'</td>
<td>'.$row['asin'].'</td>
<td>'.$row['category'].'</td>
<td>'. date('m d, Y', strtotime($row['date'])) .'</td>
<td>'.$row['6am'].'</td>
<td>'.$row['8am'].'</td>
<td>'.$row['10am'].'</td>
<td>'.$row['12pm'].'</td>
</tr>';
}
mysqli_close($conn);
?>
</tbody>
</table>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script rel="script" type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script rel="script" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.js"></script>
<script rel="script" type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.js"></script>
</body>
</html>
Try to write
$display = "SELECT * FROM user_input";
$result = mysqli_query($conn, $display);
if (!$result) {
die ('SQL Error: ' . mysqli_error($conn));
}
block out side of the condition.

query is not running in php

Hi there i am trying to create a screen in php.
in which i select scenario and the screen displayed accordingly.
but i am stuck in a simple problem that my simple select query is not working
which is
$deptQuery = "Select * from mcb_department";
echo mysql_real_escape_string($deptQuery);
mysql_query($deptQuery) or die("adfasdf");
in same code if change the table name it just work fine, also this table is created in the db as well with the same name i have shared.
here is my complete code.
<?php
include "include/conn.php";
include "include/session.php";
if(isset($_SESSION['logged_user']) && $_SESSION['logged_user'] != '99999'){
header('location: login.php');
}
$query = mysql_query("select curdate() as todayDate");
$show = mysql_fetch_array($query);
if(isset($show)){
$todayDate= $show['todayDate'];
}
$group[] = array();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta Content="no-cache, no-store, must-revalidate" http-Equiv="Cache-Control" />
<meta Content="no-cache" http-Equiv="Pragma" />
<meta Content="0" http-Equiv="Expires" />
<link href="styles/style.css" type="text/css" rel="stylesheet" />
<link href="styles/popupstyle.css" type="text/css" rel="stylesheet" />
<link href="styles/ts.css" type="text/css" rel="stylesheet" />
<link href="styles/calendar.css" type="text/css" rel="stylesheet" />
<style>
table {
font-family: arial;
border-collapse: collapse;
width: 100%;
font-size: 11px;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 3px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body >
</body>
<select id='select_opt'>
<option> Select Assigment </option>
<option value="1"> assign quiz to all Employees </option>
<option value="2"> assign quiz to Sapcific Group </option>
<option value="3"> assign quiz to Sapcific Department </option>
<option value="4"> assign quiz to Sapcific Employee </option>
</select>
<!-- all Users -->
<div id='allUsers' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action="" mathod="post">
<select>
<option value=""> select Quiz</option>
</select>
<input type="submit" >
</form>
</div>
<!-- group -->
<div id='group' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action='group_assigment.php' mathod="post">
<table>
<tr>
<th>All <input type="checkbox"> </th>
<th>Group Name</th>
<th>Group Code</th>
</tr>
<?php
$group[] = array();
$groupQuery = "Select * from mcb_groups";
$query = mysql_query($groupQuery);
?>
<tr>
<?php if($query){
while($group = mysql_fetch_array($query)){
?>
<td><input type="checkbox" value="<?php echo $group['group_name']; ?>"></td>
<td><?php echo $group['group_name']; ?></td>
<td><?php echo $group['group_code']; ?></td>
</tr>
<?php }
} else{ echo "";} ?>
</table>
</form>
</div>
<!--
####################################
department
####################################
-->
<div id='Department' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action='group_assigment.php' mathod="post">
<table>
<tr>
<th>all <input type="checkbox"> </th>
<th>name</th>
<th>code</th>
<th>group</th>
</tr>
<tr>
<?php
$deptQuery = "Select * from mcb_department";
echo mysql_real_escape_string($deptQuery);
mysql_query($deptQuery);
?>
<td><input type="checkbox"></td>
<td>code</td>
<td>name</td>
<td>group</td>
</tr>
</table>
<input type="submit" >
</form>
</div>
<!--
####################################
Employee
####################################
-->
<div id='employee' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action="" mathod="post">
<label>employee id : </label><input type="text" >
<input type="submit" >
</form>
</div>
<script language="javascript" type="text/javascript">
var elem = document.getElementById("select_opt");
elem.onchange = function(){
console.log("yes i am running");
if( document.getElementById("select_opt").value == "1" ){
document.getElementById("allUsers").style.display = "Block";
document.getElementById("group").style.display = "none";
document.getElementById("Department").style.display = "none";
document.getElementById("employee").style.display = "none";
}
else if( document.getElementById("select_opt").value == "2" ){
document.getElementById("group").style.display = "Block";
document.getElementById("allUsers").style.display = "none";
document.getElementById("Department").style.display = "none";
document.getElementById("employee").style.display = "none";
}
else if( document.getElementById("select_opt").value == "3" ){
document.getElementById("Department").style.display = "block";
document.getElementById("group").style.display = "none";
document.getElementById("allUsers").style.display = "none";
document.getElementById("employee").style.display = "none";
}
else if( document.getElementById("select_opt").value == "4" ){
document.getElementById("employee").style.display = "block";
document.getElementById("Department").style.display = "none";
document.getElementById("group").style.display = "none";
document.getElementById("allUsers").style.display = "none";
}
else{
}
};
</script>
</
html>
regard,
Shafee jan
in same code if change the table name it just work fine
Then I would make sure you're connected to the right database. It's surprisingly common for developers to have multiple versions of their database, either on different MySQL instances or else on the same instance under a different schema name. Then they get mixed up, connecting to one database with MySQL Workbench while their app is connecting to a different database.
I would advise that you temporarily add a query to your page to run SHOW TABLES and then dump the result of that query to the log, to confirm that the mcb_department table is present in the database that your PHP script is connected to.
$deptQuery = "Select * from mcb_department";
echo mysql_real_escape_string($deptQuery);
mysql_query($deptQuery);
Where's your error checking? You need to check the return value of mysql_query() every time you run a query, so if there's a problem, you output the error message to your log. Only this way can you start to solve some of these problems.
$result = mysql_query($deptQuery);
if (!$result) {
trigger_error("Error in file " . __FILE__ . " near line " . __LINE__
. " for query $deptQuery: " . mysql_error());
die("Database error");
}
PS: The advice of some commenters that mysql_* functions are deprecated is true, but probably irrelevant to your question. Folks who focus on the API, when you have said the API is working, are just being pedantic.

PHP: global variable not being stored?

It turns out this has nothing to do with global variables (sorry discussed in another post).
I was trying to keep all the code on one page (self-processing), but I'm pretty sure it's not possible. Arranging the following code outlined in the answer below, on the same page, does not work. Figures.
*edited to add the whole script minus the CSS (unnecessary).
<!DOCTYPE html>
<head>
<title>Inventory Tables</title>
</head>
<style></style>
<body>
<?php //IRCinventoryhome.php
require("IRCpage.inc");
require_once 'IRCinventoryconfig.php';
$homepage = new IRCtemplate();
$homepage->Display();
session_start();
?>
<!-- Dropdown Menu for Table Selection -->
<div id="contentHeader">
<?php //Menu for table selection
ini_set('display_errors',1); error_reporting(E_ALL);
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$result = $connection->query("SHOW TABLES");
$table = array();
while ($row = $result->fetch_row()){
$table[] = $row[0];
}
$count = count($table);
?>
<div id="select">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<select name="value">
<?php for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
echo <<<_END
<pre>
<option value="$table[$pointer]">$table[$pointer]</option>
</pre>
_END;
}
?>
</select>
<input type="submit" value="go">
</form>
</div> <!-- End .select -->
</div> <!-- End #contentHeader -->
<div id="content">
<!-- Code for Database Tables and Actions -->
<?php //inventory mysql tables
if (($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['value'])) {
$thisTable = $_POST['value'];
global $thisTable;
ini_set('display_errors',1); error_reporting(E_ALL);
$queryColumns = "SHOW COLUMNS FROM $thisTable";
$resultColumns = $connection->query($queryColumns);
if (!$resultColumns) die ("Database access failed: " . $connection->error);
$columns = array();
while ($column = $resultColumns->fetch_row()){
$columns[] = $column[0];
}
echo "<div id=\"table\"><table class=\"CSSTableGenerator\" >\n";
$count = count($columns);
$insertColumns = array();
for ($pointer = 1 ; $pointer < $count ; ++$pointer) {
$insertColumns[] = $columns[$pointer];
}
for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
echo "<th scope=\"col\" bgcolor=\"#efefef\">";
echo $columns[$pointer];
echo "</th>";
}
echo "<th>ACTIONS</td>";
$queryRows = "SELECT * FROM $thisTable";
$resultRows = $connection->query($queryRows);
if (!$resultRows) die ("Database access failed: " . $connection->error);
$rows = $resultRows->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$resultRows->data_seek($j);
$row = $resultRows->fetch_array(MYSQLI_NUM);
$count = count($row);
echo "<tr>";
for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
echo "<td>";
echo $row[$pointer];
echo "</td>";
}
?>
<td>
<input action="<?php echo $_SERVER['PHP_SELF']?>" type="submit" value="edit" name="edit">
<input action="<?php echo $_SERVER['PHP_SELF']?>" type="submit" value="delete" name="delete">
</td>
</tr>
<?php
}
echo "</table></div>"; //end table, end content
$connection->close();
}
?>
<!-- FORM FOR ADDING ROWS TO CURRENT TABLE -->
<div id="table">
<table id="formTable">
<form name="addRow" action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type="hidden" name="control">
<td>
Add row?
</td>
<?php for ($pointer = 1 ; $pointer < $count ; ++$pointer) { ?>
<td>
<input type="text" name="<?php echo $columns[$pointer];?>">
</td>
<?php } ?>
<td>
<input type="submit" value="go">
</td>
</form>
</table>
</div> <!-- end form, end table, end content -->
<?php
global $thisTable;
echo $thisTable;
if (isset($_POST['control'])) {
global $thisTable;
echo $thisTable;
$valuesArray = array();
if (isset($_POST)) {
$valuesArray = $_POST;
}
$columnsArray = array_keys($valuesArray);
//array_splice($columnsArray, 0, 1);
$columnsString = implode(", ", $columnsArray);
print_r($columnsString);
$insertValues = array();
foreach($valuesArray as $values) {
$insertValues[] = $values;
}
$valuesString = implode(" ", $insertValues);
$valuesString = "'".$valuesString."'";
$valuesString = str_replace(" ", "', '", $valuesString);
$valuesString = substr($valuesString, 3);
print_r($valuesString);
/*
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$queryInsert = "INSERT INTO $thisTable ($columnsString) VALUES ($valuesString)";
$result = $connection->query($queryInsert);
if (!$result) echo "INSERT failed: $query<br>" .
$connection->error . "<br><br>";
$connection->close();
*/
}
?>
</div> <!-- End #content -->
</body>
</html>
After 20 hours or so I'm still not sure if this possible to do all on the same page. But this solution works...
Page one:
<!DOCTYPE html>
<head>
<title>Interactive Resource Center Inventory</title>
<meta charset="UTF-8">
</head>
<script src="../_js/jquery.min.js"></script>
<script src="../_js/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$('form').submit(function() {
$('input[type=submit]')
prop('disabled',true);
});//end submit
var max_fields = 4; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div>Column: <input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});//end ready
</script>
<style>
#table {
margin-top:2px;
}
#formTable {
width:100%;
margin:0px;padding:0px;
border:1px solid #000000;
border-bottom:none;
border-left:none;
border-right:none;
}
#formTable td{
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
width:100px;
font-size:14px;
font-family:arial;
font-weight:normal;
color:#000000;
}
#formTable input[type="text"]{
width:95%;
}
.CSSTableGenerator {
margin:0px;padding:0px;
width:100%;
border:1px solid #000000;
border-top:none;
border-right:none;
border-left:none;
}
.CSSTableGenerator table{
width:100%;
height:100%;
margin:0px;padding:0px;
}
.CSSTableGenerator tr:nth-child(odd){ background-color:#e5e5e5; }
.CSSTableGenerator tr:nth-child(even) { background-color:#ffffff; }
.CSSTableGenerator th{
border:1px solid #000000;
border-width:0px 1px 1px 0px;
width:100px;
}
.CSSTableGenerator td{
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
width:100px;
font-size:14px;
font-family:arial;
font-weight:normal;
color:#000000;
}
.CSSTableGenerator tr:last-child td{
border-width:0px 1px 0px 0px;
}
.CSSTableGenerator tr td:last-child{
border-width:0px 0px 1px 0px;
}
.CSSTableGenerator tr:last-child td:last-child{
border-width:0px 0px 0px 0px;
}
.CSSTableGenerator tr:first-child td{
background:-o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) ); background:-moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#b2b2b2"); background: -o-linear-gradient(top,#cccccc,b2b2b2);
background-color:#cccccc;
border:0px solid #000000;
text-align:center;
border-width:0px 0px 1px 1px;
font-size:14px;
font-family:arial;
font-weight:bold;
color:#000000;
margin-top:-2px;
</style>
<body>
<?php //IRCinventoryhome.php
require("IRCpage.inc");
require("IRCinventoryfunctions.php");
require_once 'IRCinventoryconfig.php';
$homepage = new IRCtemplate();
$homepage->Display();
session_start();
$_SESSION['value'] = $_POST['value'];
$thisTable = $_SESSION['value'];
var_dump($_SESSION);
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
if ($connection->connect_error) die($connection->connect_error);
global $connection;
$result = $connection->query("SHOW TABLES");
$table = array();
while ($row = $result->fetch_row()){
$table[] = $row[0];
}
$count = count($table);
?>
<!-- Dropdown Menu for Table Selection -->
<div id="contentHeader">
<div id="select">
<form action="http://localhost:8888/IRC/IRCinventoryhometest.php" method="POST">
<select name="value">
<?php for ($pointer = 0 ; $pointer < $count ; ++$pointer) {
echo <<<_END
<pre>
<option value="$table[$pointer]">$table[$pointer]</option>
</pre>
_END;
}
?>
</select>
<input type="submit" name="go">
</form>
</div> <!-- End .select -->
</div> <!-- End #contentHeader -->
<div id="content">
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$thisTable = "OUTGOING";
$queryColumns = "SHOW COLUMNS FROM $thisTable";
$resultColumns = $connection->query($queryColumns);
if (!$resultColumns) die ("Database access failed: " . $connection->error);
global $resultColumns;
$queryRows = "SELECT * FROM $thisTable";
$resultRows = $connection->query($queryRows);
if (!$resultRows) die ("Database access failed: " . $connection->error);
global $resultRows;
$rows = $resultRows->num_rows;
global $rows;
global $connection;
drawTable();
$connection->close();
} else {
if(isset($_POST['value'])) {
$thisTable = $_POST['value'];
}
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
if ($connection->connect_error) die($connection->connect_error);
global $connection;
$queryColumns = "SHOW COLUMNS FROM $thisTable";
$resultColumns = $connection->query($queryColumns);
if (!$resultColumns) die ("Database access failed: " . $connection->error);
global $resultColumns;
$queryRows = "SELECT * FROM $thisTable";
$resultRows = $connection->query($queryRows);
if (!$resultRows) die ("Database access failed: " . $connection->error);
global $resultRows;
$rows = $resultRows->num_rows;
global $rows;
global $connection;
drawTable();
?>
<!-- FORM FOR ADDING ROWS TO CURRENT TABLE -->
<div id="table">
<table id="formTable">
<form name="addRow" action="http://localhost:8888/IRC/IRCprocessinventory.php" method="POST">
<input type="hidden" name="control">
<td>
Add row?
</td>
<td></td>
<?php for ($pointer = 2 ; $pointer < $countColumnsGlobal ; ++$pointer) { ?>
<td>
<input type="text" name="<?php echo $columns[$pointer];?>">
</td>
<?php } ?>
<td>
<input type="submit" value="submit">
</td>
</form>
</table>
</div> <!-- end table -->
<?php
}
?>
</div> <!-- End #content -->
</body>
</html>
Page 2:
<?php
require_once 'IRCinventoryconfig.php';
ini_set('display_errors',1); error_reporting(E_ALL);
session_start();
if(isset($_SESSION['value'])) {
$thisTable = $_SESSION['value'];
$valuesArray = array();
if (isset($_POST)) {
$valuesArray = $_POST;
}
$columnsArray = array_keys($valuesArray);
array_splice($columnsArray, 0, 1);
$columnsString = implode(", ", $columnsArray);
$insertValues = array();
foreach($valuesArray as $values) {
$insertValues[] = $values;
}
$valuesString = implode("','", $insertValues);
$valuesString = "'".$valuesString."'";
$valuesString = substr($valuesString, 3);
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
if ($connection->connect_error) die($connection->connect_error);
$queryInsert = "INSERT INTO $thisTable ($columnsString) VALUES ($valuesString)";
$result = $connection->query($queryInsert);
if (!$result) echo "INSERT failed: $query<br>" .
$connection->error . "<br><br>";
else echo "Successful entry";
$connection->close();
}
?>

Categories