I've been trying to solve this for awhile, and I'd appreciate it if someone can help me. Here is my problem.
Here is my code; it's simply view the content of a Job Table in the Database and perform a edition as needed, based on the selection. The checkbox is next to each job, and there is an update button at the end of the page to submit..
I'm getting an error updating it. Please help me.
<?php
session_start();
if( isset($_SESSION['username']) ){
include('../CIEcon.php');
echo "<form action= 'adminCleaning.php' method = 'post'>" ;
// when the user click update..
if(isset($_POST['update'])){
if( empty($_POST['Id']) || $_POST['Id'] == 0 ){
echo"<h4> please choose something to update </h4>";
echo"test(1): pass <br> ";
}else{
// comes here even though u dind't chhose, cause
// it set IDs next to each feild..
echo"!!....HERE....!! ";
}
}// end of update $_POAT[update]
$sql = "SELECT * FROM Cleaning ";
$result = mysqli_query($dbCIE, $sql) or die(mysqli_error($dbCIE));
/// NOW DISPLAY ALL INFO FROM CHOSEN DATABASE...
echo "
<table cellpadding ='4' border='1' width='80%' align='center'>
<tr>
<th class='tt' >Check </th>
<th class='tt'> Job's Name</th>
<th class='tt' >Description</th>
<th class='tt' > No Students needed</th>
<th class='tt' >Due Date</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<br>";
echo "<tr>";
echo "<td> <input type='checkbox' name='Id[]' value='".$row['Id']."' /> </td>"; // array[] cause to edit more than one record...
echo "<td>".'<input type="text" name="jobname['.$row['Id'].']" value='.$row['JobName'].' >'."</td>";
echo "<td>".'<input type="text" name="description['.$row['Id'].']" value='.$row['Description'].'> '."</td>";
echo "<td>".'<input type="text" name="nostudent['.$row['Id'].']" value='.$row['NoStudent'].'>'."</td>";
echo "<td>".'<input type="text" name="duedate['.$row['Id'].']" value='.$row['DueDate'].'>'."</td>";
echo "<input type=hidden name='Id[]' value='".$row['Id']."' >";
echo "</tr>";
echo "jobname['.$row[Id].']" ; // testing.
echo "description['.$row[Id].']" ; // testing.
echo "nostudent['.$row[Id].']" ; // testing.
}
echo "</table>";
/// END THE SEARCH HERE...........
echo " <br>
<div align='center'>
<input type='reset' value='clear' />
<input type='submit' name='update' value='update' />
</div> ";
mysqli_close($dbCIE);
echo "</form>";
}
else{echo "must logout to see this page..!!";}
?>
<html>
<head><title> ..Cleanding.... </title></head>
<style type="text/css">
body{
margin-top: 70px; /*space above the table....*/
background-color: #23438e;
}
table{
background-color: white;
}
.tt{
background: #f26822;
color: white ;
}
</style>
<body>
<!-- <a href= "../AdminIndex.php" > <button> Main Page </button></a> -->
</body>
</html>
First of all, your form and table are outside of <body> tag. You have to display everything like this: <body> **display here** </body>
Second, remove this line echo "<input type=hidden name='Id[]' value='".$row['Id']."' >"; from your code, it's not required.
And now comes to your question, $_POST['Id'] is an array of job ids, so use count() function to check if the array is empty or not and use foreach loop to update each individual row. So you should process your form like this:
// when the user click update..
if(isset($_POST['update'])){
if(count($_POST['Id'])){
// $_POST['Id'] is an array of job id
foreach($_POST['Id'] as $v){
$sqlUpdate = "UPDATE Cleaning SET JobName='" . $_POST['jobname'][$v] . "', Description='" . $_POST['description'][$v] . "', NoStudent='" . $_POST['nostudent'][$v] ."', DueDate='" . $_POST['duedate'][$v] . "' WHERE Id = '" . $v . "'";
$resultUpdate = mysqli_query($dbCIE,$sqlUpdate) or die(mysqli_error($dbCIE));
// If you want you can use mysqli_affected_rows() function to
// check how many were affected by the UPDATE query
}
}else{
echo"<h4>please choose something to update</h4>";
}
}
And your entire code should be like this:
<?php
session_start();
?>
<html>
<head>
<title> ..Cleanding.... </title>
<style type="text/css">
body{
margin-top: 70px; /*space above the table....*/
background-color: #23438e;
}
table{
background-color: white;
}
.tt{
background: #f26822;
color: white ;
}
</style>
</head>
<body>
<?php
if( isset($_SESSION['username']) ){
include('../CIEcon.php');
// when the user click update..
if(isset($_POST['update'])){
if(count($_POST['Id'])){
// $_POST['Id'] is an array of job id
foreach($_POST['Id'] as $v){
$sqlUpdate = "UPDATE Cleaning SET JobName='" . $_POST['jobname'][$v] . "', Description='" . $_POST['description'][$v] . "', NoStudent='" . $_POST['nostudent'][$v] ."', DueDate='" . $_POST['duedate'][$v] . "' WHERE Id = '" . $v . "'";
$resultUpdate = mysqli_query($dbCIE,$sqlUpdate) or die(mysqli_error($dbCIE));
// If you want you can mysqli_affected_rows() function to
// check how many were affected by the UPDATE query
}
}else{
echo"<h4>please choose something to update</h4>";
}
}
$sql = "SELECT * FROM Cleaning ";
$result = mysqli_query($dbCIE, $sql) or die(mysqli_error($dbCIE));
?>
<form action= 'adminCleaning.php' method = 'post'>
<table cellpadding ='4' border='1' width='80%' align='center'>
<tr>
<th class='tt' >Check </th>
<th class='tt'> Job's Name</th>
<th class='tt' >Description</th>
<th class='tt' > No Students needed</th>
<th class='tt' >Due Date</th>
</tr>
<?php
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td> <input type="checkbox" name="Id[]" value="<?php echo $row['Id']; ?>" /> </td>
<td><input type="text" name="jobname[<?php echo $row['Id']; ?>]" value="<?php echo $row['JobName']; ?>" /></td>
<td><input type="text" name="description[<?php echo $row['Id']; ?>]" value="<?php echo $row['Description']; ?>" /></td>
<td><input type="text" name="nostudent[<?php echo $row['Id']; ?>]" value="<?php echo $row['NoStudent']; ?>" /></td>
<td><input type="text" name="duedate[<?php echo $row['Id']; ?>]" value="<?php echo $row['DueDate']; ?>" /></td>
</tr>
<?php
}
?>
</table>
<input type="reset" value="clear" />
<input type="submit" name="update" value="update" />
</form>
<br />
<div align='center'>
</div>
<?php
mysqli_close($dbCIE);
}
else{
echo "must logout to see this page..!!";
}
?>
</body>
</html>
Related
currently I have created a system that can perform multiple delete actions for a list of data rows that fetch from a SQL database and display at dashboard_engineer.php. Each data row contains a delete button. Each row also has a checkbox that enables the user to delete selected data rows. At the bottom of the data rows, there's a button to delete all the selected data rows.
My problem is on multiple delete, lets say, if I select two data rows, (id 4 and 5) it will only delete one ID.
Below is my code
dashboard_engineer2.php
<?php
if(isset($_REQUEST['from'], $_REQUEST['to'], $_REQUEST['team'])){
$from = $_REQUEST['from'];
$to = $_REQUEST['to'];
$team = $_REQUEST['team'];
$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid
WHERE ot_report.status = 'yes' AND ot_users.team_id = :team AND report_date BETWEEN :from
AND :to ORDER BY ot_report.report_id DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql->bindParam(':team', $team);
$sql->bindParam(':from', $from);
$sql->bindParam(':to', $to,);
$sql -> execute();
if($sql->rowCount() > 0){
echo'
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th width = "10%"><input type="checkbox" id="checkAl"> All</th>
<th width = "3%">id</th>
<th width = "15%">Date</th>
<th width = "25%">Supervisor</th>
<th width = "30%">Task Name</th>
<th width = "10%">Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$status=$row['report_status'];
if($status=="Pending"){
$color="color:blue";
}
else {
$color="color:green";
}
$report_id = $row["report_id"];
echo'<tr>';
echo '<td><input type="checkbox" id="checkItem" name="check[]" value="'.$report_id.'"></td>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$row['report_date'].'</td>';
echo '<td>'.$row["fullname"].'</td>';
echo '<td>'.$row["task_name"].'</td>';
echo '<td align="center" style='.$color.'><strong>'.$status.'</strong></td>';
echo '<td align="center">';
echo '<form action = "view_task/view_task.php" method = "post" target="_blank">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-primary">View</button>';
echo '</form>';
echo '</td>';
echo '<td align="center">';
echo "<form action = 'remove2.php' method = 'post' onClick=\"return confirm('Do you want to remove this reports?')\">";
echo '<input type = "hidden" name = "from" value = "'.$from.'">';
echo '<input type = "hidden" name = "to" value = "'.$to.'">';
echo '<input type = "hidden" name = "team" value = "'.$team.'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Remove</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
$i++;
}
echo '<tr>';
echo '<td>';
echo "<form action = 'delete_selected.php' method = 'post'>";
echo '<input type="hidden" id="checkItem" name="check[]" value="'.$report_id.'">';
echo '<button type="submit" class="btn-danger btn-sm">DELETE</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
}
}
?>
delete_selected.php
<?php
include("../../../config/configPDO.php");
include("../../../config/check.php");
$checkbox = $_POST['check'];
for($i=0;$i<count($checkbox);$i++){
$report_id = $checkbox[$i];
$sql = "UPDATE ot_report SET status = 'no' WHERE report_id=:report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php");
}
?>
Can anyone help me to solve this problem? Thanks
OK - the following is based upon the question's code but in order to build a working demo it has been generalised. The important thing here is the use of Javascript to maintain the list of IDs selected ( either by clicking the select-all checkbox or by clicking individual checkboxes. Please ignore the content generated in the form - the dates are spurious and meaningless to this example.
You could copy this and create a test page which should run OK - the PHP that generates the pseudo SQL is simply to display the statements that would be executed and not how it should be executed ( should be as per question, prepared statement )
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( isset( $_POST['ids'] ) ){
$items=explode( ',', $_POST['ids'][0] );
foreach($items as $id){
$sql=sprintf('UPDATE ot_report SET status="no" WHERE report_id=%d',$id);
echo $sql . '<br />';
}
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<table>
<?php
for( $i=1; $i <= 10; $i++ ){
/* example data for dates... */
$hrs=mt_rand(1,24);
$mins=mt_rand(0,60);
$secs=mt_rand(0,60);
$month=mt_rand(1,12);
$day=mt_rand(1,28);
$year=mt_rand(2000,2020);
$from=date('y-m-d',mktime($hrs,$mins,$secs,$month,$day,$year));
$to=date('y-m-d',mktime($hrs+3,$mins+20,$secs,$month,$day,$year));
printf('
<tr>
<td><input type="checkbox" name="check[]" value="%1$d" /></td>
<td>Some data %1$d</td>
<td>
<form method="post">
<input type="hidden" name="from" value="%2$s" />
<input type="hidden" name="to" value="%3$s" />
<input type="hidden" name="id" value="%1$d" />
<input type="submit" />
</form>
</td>
</tr>', $i, $from, $to );
}
?>
</table>
<form method='post'>
<input type='checkbox' name='selectall' value='Select-All' />
<input type='hidden' name='ids[]' />
<input type='button' name='sub-delete' value='Update selected' />
</form>
<script>
let ids=document.querySelector('input[type="hidden"][name="ids[]"]');
let tmp=[];
document.querySelector('[name="selectall"]').addEventListener('change',function(e){
let col=document.querySelectorAll('[name="check[]"]');
col.forEach(chk=>{
chk.checked=this.checked;
if( this.checked )tmp.push(chk.value)
else tmp.splice(tmp.indexOf(chk.value),1)
});
});
document.querySelectorAll('[name="check[]"]').forEach( chk=>{
chk.addEventListener('change',function(e){
if( this.checked )tmp.push(this.value)
else tmp.splice( tmp.indexOf(this.value),1);
});
});
document.querySelector('[name="sub-delete"]').addEventListener('click',function(e){
ids.value=tmp.join(',')
this.parentNode.submit()
});
</script>
</body>
</html>
Will generate something akin to:
UPDATE ot_report SET status="no" WHERE report_id=10
UPDATE ot_report SET status="no" WHERE report_id=8
UPDATE ot_report SET status="no" WHERE report_id=6
UPDATE ot_report SET status="no" WHERE report_id=4
Quickly trying to adapt this example with your code :
<?php
if(isset($_REQUEST['from'], $_REQUEST['to'], $_REQUEST['team'])){
$from=$_REQUEST['from'];
$to =$_REQUEST['to'];
$team=$_REQUEST['team'];
$result='';
$query="SELECT * FROM ot_report
LEFT JOIN ot_users ON ot_report.badgeid=ot_users.badgeid
WHERE ot_report.status='yes' AND ot_users.team_id=:team AND report_date BETWEEN :from AND :to
ORDER BY ot_report.report_id DESC";
$sql=$conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql->bindParam(':team', $team);
$sql->bindParam(':from', $from);
$sql->bindParam(':to', $to);
$sql->execute();
if($sql->rowCount() > 0){
echo'
<table class="table-bordered" width="100%">
<thead>
<tr>
<th width="10%"><input type="hidden" name="selectall" value="Select-All">All</th>
<th width="3%">id</th>
<th width="15%">Date</th>
<th width="25%">Supervisor</th>
<th width="30%">Task Name</th>
<th width="10%">Status</th>
<th colspan="2" width="7%">Action</th>
</tr>
</thead>
<tbody>';
$i=0;
while($row=$sql->fetch(PDO::FETCH_ASSOC)){
$status=$row['report_status'];
if($status=="Pending"){
$color="color:blue";
} else {
$color="color:green";
}
$report_id=$row["report_id"];
echo'
<tr>
<td><input type="checkbox" name="check[]" value="'.$report_id.'"></td>
<td>'.$report_id.'</td>
<td>'.$row['report_date'].'</td>
<td>'.$row["fullname"].'</td>
<td>'.$row["task_name"].'</td>
<td align="center" style='.$color.'><strong>'.$status.'</strong></td>
<td align="center">
<form action="view_task/view_task.php" method="post" target="_blank">
<input type="hidden" name="report_id" value="'.$report_id.'">
<button type="submit" class="btn-primary">View</button>
</form>
</td>
<td align="center">
<form action="remove2.php" method="post" onsubmit="return confirm(\'Do you want to remove this reports?\')">
<input type="hidden" name="from" value="'.$from.'">
<input type="hidden" name="to" value="'.$to.'">
<input type="hidden" name="team" value="'.$team.'">
<input type="hidden" name="report_id" value="'.$report_id.'">
<button type="submit" class="btn-danger">Remove</button>
</form>
</td>
</tr>';
$i++;
}
echo '
<tr>
<td>
<form action="delete_selected.php" method="post">
<input type='hidden' name='ids[]' />
<input type='button' name='sub-delete' value='DELETE' />
</form>
</td>
</tr>';
}
}
?>
<script>
let ids=document.querySelector('input[type="hidden"][name="ids[]"]');
let tmp=[];
document.querySelector('[name="selectall"]').addEventListener('change',function(e){
let col=document.querySelectorAll('[name="check[]"]');
col.forEach(chk=>{
chk.checked=this.checked;
if( this.checked )tmp.push(chk.value)
else tmp.splice(tmp.indexOf(chk.value),1)
});
});
document.querySelectorAll('[name="check[]"]').forEach( chk=>{
chk.addEventListener('change',function(e){
if( this.checked )tmp.push(this.value)
else tmp.splice( tmp.indexOf(this.value),1);
});
});
document.querySelector('[name="sub-delete"]').addEventListener('click',function(e){
ids.value=tmp.join(',')
this.parentNode.submit()
});
</script>
and
delete_selected.php
<?php
include("../../../config/configPDO.php");
include("../../../config/check.php");
$checkbox=explode( ',', $_POST['ids'][0] );
for($i=0;$i < count($checkbox); $i++){
$report_id=$checkbox[$i];
$sql="UPDATE ot_report SET status='no' WHERE report_id=:report_id";
$query=$conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php");
}
?>
I am trying to update multiple rows simultaneously and I think my query is somewhat messed up while i am trying to update all my rows simultaneously. I am using CodeIgniter framework. I want to work on my query and the data being sent from the view but unable to get a logic to update all rows simultaneously. Please note that there should be only one update button as this is a requirement
My View code is:
<form action="" method="post">
<table border="1" style="background:none;width:100%;" RULES="ROWS" class="tab_data">
<thead>
<th width="30px">No</th>
<th >Action Item</th>
<th>Responsibility</th>
<th>Order</th>
<th>Mandatory?</th>
<th width = "100px" align="center">Actions</th>
</thead>
<tbody>
<?php
$serial_no = 1;
if(count($rows))
{
foreach($rows as $row)
{
?>
<tr>
<td><?php echo $serial_no; ?></td>
<td>
<?php
echo "<input type='hidden' class='col-md-4 form-control' name='checklist_id' value='"
.$row['checklist_id']."' />";
echo $row['action_item'];
?>
</td>
<td>
<?php echo $row['responsibility']; ?>
</td>
<td>
<input type="hidden" name="row_id[]" value="<?php echo $row['sequence']; ?>">
<input type="text" class="form-control" name="order[]" value="<?php echo $row['sequence']; ?>">
</td>
<td>
<input type="checkbox" class="" name="if_checklist<?php echo $row->checklist_id; ?>" value="1" echo 'checked'; >
</td>
<td align="center">
<?php
echo anchor('exits/delete_absconding_checklist/'.$row['checklist_id'],
"<i class='fa fa-trash-o' alt='Delete' title='Delete' rel='".$row['id']."' ></i>",
array('rel' => $row->id, 'class' => 'edit_row'));
?>
</td>
</tr>
<?php
$serial_no++;
}
}
?>
<tr>
<td></td><td></td><td></td><td></td>
<td>
<input type="hidden" name="action" value="update_order">
<button type="submit" name="submit" class="btn btn-info pull-right">Update</button>
</td>
</tr>
</tbody>
</table>
</form>
My Controller Code is:
function display_absconding_checklist()
{
if($this->input->post('action') == '_doDelete' || $this->input->post('action') == '_doChangeStatus')
{
$this->admin_init_elements->delete_rows('applicant_status');
}
if($this->input->post('action') == 'update_order')
{
$this->exit_common->update_absconding_checklist();
}
$data['rows'] = $this->exit_common->get_all_absconding_checklists();
$this->data['maincontent'] = $this->load->view('maincontents/backend_display_absconding_checklist', $data, true);
$this->load->view('layout', $this->data);
}
My Model code is:
function update_absconding_checklist($post_array)
{
$post_array = $this->input->post();
foreach($post_array['checklist_id'] as $key => $rowid)
{
if($rowid > 0)
{
if(isset($post_array['if_checklist'.$rowid]))
$in = '1';
else
$in = '0';
$sql1 = "UPDATE pr_absconding_checklists SET `action_item` = '"
.$post_array['action_item'][$key]
."', `sequence` = '".$post_array['sequence'][$key]
."', `if_checklist` = '".$in
."' WHERE `checklist_id` = ".$rowid;
}
else
{
$sql1 = "UPDATE pr_absconding_checklists SET `action_item` = '"
.$post_array['action_item'][$key]
."', `sequence` = '".$post_array['sequence'][$key]
."', `if_checklist` = '".$in."'";
}
$query1 = $this->db->query($sql1);
}
}
I am getting no errors but there are many errors in my code and i am messed up, i am attaching my table snapshot also, please recommend improvements
My Table name is pr_absconding_checklists
i'm creating asset database system (just an offline system, not connected to internet) that will show all assets list. on the list, i can click on any asset to view the details. also i'm manage to update the details or delete the asset. but when it goes to asset record parts, it give an error on inserting record to asset using a form.
here is my record add form. and i'm also wanna make machine id visible under MACHINE ID field in the form, but i did't know yet how to put the data there.
for inserting record, its will capture machine id on rekod_add.php ( record add) url address from asset table to passing into rekod_tab table.
here is my record add page ( rekod_add.php )
<?php
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['username']) || (trim($_SESSION['password']) == '')) {
header("location: login.php");
exit();
}
?>
<html>
<head>
<title>EXA_mySQL</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
body,td,th {
font-family: Tahoma, Geneva, sans-serif;
}
</style>
</head>
<body>
<script type="text/javascript">function checkinput() {
var id_mesin = document.getElementById('id_mesin').value;
if(!id_mesin.match(/\S/)) {
alert ('Please enter Machine ID');
return false;
} else {
return true;
}
}
</script>
<?php
$con=mysqli_connect("localhost","root","admin","exa");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id_mesin = $_POST['id_mesin'];
$query = "SELECT * FROM asset WHERE id_mesin ='".$id_mesin."'";
$result = mysqli_query($con,$query);
$rows = mysqli_fetch_array($result);
?>
<table width="733" border="0" align="center" cellpadding="0" cellspacing="1">
<tr>
<td><form name="form_insert" method="post" action="rekod_add_ac.php">
<table width="709" border="0" align="center">
<tr>
<th width="23" scope="col">MACHINE ID</th>
<th colspan="2" scope="col">DATE</th>
<th width="68" scope="col">TIME</th>
<th width="175" scope="col">RECEIVE CALL BY</th>
<th width="97" scope="col">CURRENT METER</th>
<th width="90" scope="col">LAST METER</th>
<th width="136" scope="col">J.SHEET NO</th>
</tr>
<tr>
<td> </td>
<td colspan="2"><input name="tarikh_rekod" type="text" id="tarikh_rekod" size="15" /></td>
<td><input name="time" type="text" id="time" size="10" maxlength="9" /></td>
<td><input type="text" name="call_by" id="call_by" /></td>
<td><input name="meter_semasa" type="text" id="meter_semasa" size="15" /></td>
<td><input name="meter_last" type="text" id="meter_last" size="15" /></td>
<td><input name="rujukan" type="text" id="rujukan" size="10" /></td>
</tr>
<tr>
<td> </td>
<th width="81">PROBLEM</th>
<th width="5">:</th>
<td colspan="3"><textarea name="masalah" id="masalah" cols="55" rows="5"></textarea></td>
<th colspan="2" rowspan="2"><p>REMARK</p>
<p>
<textarea name="remark" cols="30" rows="6" id="remark"></textarea>
</p></th>
</tr>
<tr>
<td> </td>
<th>SOLUTION</th>
<th>:</th>
<td colspan="3"><textarea name="solution" id="solution" cols="55" rows="5"></textarea></td>
</tr>
<tr>
<td colspan="8" align="right"><?php echo "<input type='hidden' value='" . $rows['id_mesin'] . "' name='id_mesin'>"; echo "<input type='submit' value='Add Record'>";?></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
<?php
mysqli_close($con);
?>
</body>
</html>
here is my rekod_add_ac.php
<?php
session_start();
if(!isset($_SESSION['username']) || (trim($_SESSION['password']) == '')) {
header("location: login.php");
exit();
}
?>
<html>
<head>
<title>EXA_mySQL</title>
<script type="text/javascript">
<!--
function CloseWindow() {
window.close();
window.opener.location.reload();
}
//-->
</script>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors','on');
$con=mysqli_connect("localhost","root","admin","exa");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
print_r($_POST);
$id_mesin=$_POST['id_mesin'];
$tarikh_rekod=$_POST['tarikh_rekod'];
$time=$_POST['time'];
$call_by=$_POST['call_by'];
$meter_semasa=$_POST['meter_semasa'];
$meter_last=$_POST['meter_last'];
$rujukan=$_POST['rujukan'];
$masalah=$_POST['masalah'];
$solution=$_POST['solution'];
$remark=$_POST['remark'];
$rekod_in="INSERT INTO rekod_tab ( id_mesin, tarikh_rekod, time, call_by, meter_semasa, meter_last, rujukan, masalah, solution, remark) VALUES ( $'id_mesin', $'tarikh_rekod', $'time', $'call_by', $'meter_semasa', $'meter_last', $'rujukan', $'masalah', $'solution', $'remark')";
$result=mysqli_query($con, $rekod_in);
if($result){
echo "Successful";
echo "<BR>";
echo "<th><form>";
echo "<input type='button' onClick='CloseWindow()' value='Back to Exa_mySQL' align='middle'>";
echo "</form></th>";
}
else {
echo "Data error, please recheck before submit.";
echo "<BR>";
echo "Click back to add record.";
echo "<BR>";
echo "<form action='rekod_add.php?id=$id_mesin' method='post'>";
echo "<td><input type='hidden' value='$id_mesin' name='id_mesin'>";
echo "<input type='submit' value='Back'></td>";
echo "</form>";
echo "<th><form>";
}
mysqli_close($con);
?>
</body>
</html>
after user done inserting record details, the form will add the record on rekod_tab table including machine id ( id_mesin ) which automatically capture from url like i said before.
but the result is error. when inserting detail manual in sql, its work. can anyone help me?
here my error result.
sorry for my bad english.
Try INSERT query like this
$rekod_in="INSERT INTO rekod_tab
( id_mesin, tarikh_rekod, time, call_by, meter_semasa, meter_last,
rujukan, masalah, solution, remark)
VALUES ( '$id_mesin', '$tarikh_rekod', '$time', '$call_by', '$meter_semasa',
'$meter_last', '$rujukan', '$masalah', '$solution', '$remark')";
This code here is working perfectly well. All i want to do is to pass the FirstName and LastName (using SESSION) which is already stored in the $userName. The first and last name is actually retrieved from the database when trying to login.
I want to have the First and Last Name show on every page once logged in.. Thanks
<table width="800" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td><?php
$DisplayForm = TRUE;
$errors = 0;
if(isset($_POST['uname']) && isset($_POST['pass'])) {
include("dbconnect.php");
if($DBConnect !== FALSE){
$SQLstring = "SELECT userid, first_name, last_name FROM users WHERE username ='".
$_POST['uname']. "' and password = '".md5($_POST['pass'])."'";
$DisplayForm = FALSE;
$QueryResult = #mysql_query($SQLstring, $DBConnect);
echo mysql_error();
if (mysql_num_rows($QueryResult)=== 0){
echo "<p style='color:red;'><b> The email address/password " .
" combination is not valid.</b></p>\n";
++$errors;
$DisplayForm = TRUE;
}
else
{
$DisplayForm = FALSE;
}
}
}
if ($DisplayForm)
{?>
<form id="form1" name="loginForm" method="post" action="index.php">
<table width="800" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="93" bgcolor="#DACFAF"><strong> Username:</strong></td>
<td width="149" bgcolor="#DACFAF"><label for="textfield"></label>
<input type="text" name="uname" id="textfield" /></td>
<td width="76" bgcolor="#DACFAF"><strong>Password:</strong></td>
<td width="150" bgcolor="#DACFAF"><label for="textfield2"></label>
<input type="password" name="pass" id="pass" /></td>
<td width="196" bgcolor="#DACFAF"><input type="image" name="login" src="images/login.jpg" /> </td>
<td width="68" bgcolor="#DACFAF"> </td>
<td width="68" bgcolor="#DACFAF"><strong>Register </strong> </td>
</tr>
</table>
</form>
<?php }
else {
$Row = mysql_fetch_assoc($QueryResult);
$userID = $Row['userid'];
$userName = $Row['first_name']. " ". $Row['last_name'];
echo "<table width=780px border=0px >";
echo "<tr>";
echo "<td style='color:red;'>";
echo "<b> Welcome back, $userName!</b>";
echo "</td>";
echo"<td align='right'>";
echo "<form method='POST' action=''>";
echo "<input type='submit' name='submit' value='logout'>";
echo "</form>";
echo "</td>";
echo "</tr>";
echo "</table>";
}
?> </td>
</tr>
</table>
Assuming you know how to set $_SESSION variable.
or if not
In your log in php start a session using session_start();. after all the checking is done. Put the name inside of the $_SESSION variable.
like this
$_SESSION['username'] = $firstname.$lastname;
assuming $firstname has the user's first name and $lastname has the user's last name.
THEN:
Put session_start(); at the very beginning of your PHP file that you want to display the username.
then
$userName=$_SESSION['username'];
Put this two together at the very start of every php file you want to display the name.
Now you can use the variable $userName to display the name.
I am trying to create a Registration System using only PHP. This is an example of that. But I think I have done something wrong. I tried to find similar solution in StackOverFlow posts but didn't get any exact solution. It would be really get if someone would help me to find the error in my code below.
<?php
// POST HANDLER -->
if(isset($_POST['registerForm']))
{
conFunc(); // Connection Function
$userid = $_POST['userid'];
$name = $_POST['name'];
$getUserId = mysql_query("SELECT * FROM `user` WHERE `userid` = '".$userid."'");
$id = mysql_fetch_array($getUserId);
if($id)
{
echo "This User ID is Already Available on the System, Please Choose Something Else!";
}
else
{
$query = mysql_query("INSERT INTO `user` (`userid`, `name`");
if($query)
{
echo "A New User is Registered Successfully:<br /><br />";
echo "<b>User ID:</b> " . $userid . "<br />";
echo "<b>User Name:</b> " . $name . "<br />";
}
else
{
echo "There is an Error while Saving: " . mysql_error();
echo "<br />Please click on Create User from menu, and try again<br /><br />.";
}
}
exit;
}
// POST HANDLER -->
?>
<!-- FORM GOES BELOW -->
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" name="registerForm">
<table style="width: 100%">
<tr>
<td>User ID</td>
<td><input name="userid" type="text" style="width: 300px" /><br /></td>
</tr>
<tr>
<td>Name</td>
<td><input name="name" type="text" style="width: 300px" /><br /></td>
</tr>
<tr>
<td></td>
<td><input style="width: 130px; height: 30px" type="submit" name="submit" value="Register Now" /><br /></td>
</tr>
</table>
</form>
You have to check the submit button is set or not.
if(isset($_POST['registerForm']))
should be
if(isset($_POST['submit'])) {
// your php code
} else {
// your html code
}
registerform element is not treated as post element so check with submit button.
Try following code :
<?php
// POST HANDLER -->
if(isset($_POST['submit'])){
conFunc(); // Connection Function
$userid = $_POST['userid'];
$name = $_POST['name'];
$getUserId = mysql_query("SELECT * FROM `user` WHERE `userid` = '".$userid."'");
$id = mysql_fetch_array($getUserId);
if($id)
{
echo "This User ID is Already Available on the System, Please Choose Something Else!";
}
else
{
$query = mysql_query("INSERT INTO `user` (`userid`, `name`");
if($query)
{
echo "A New User is Registered Successfully:<br /><br />";
echo "<b>User ID:</b> " . $userid . "<br />";
echo "<b>User Name:</b> " . $name . "<br />";
}
else
{
echo "There is an Error while Saving: " . mysql_error();
echo "<br />Please click on Create User from menu, and try again<br /><br />.";
}
}
exit;
}else{
// POST HANDLER -->
?>
<!-- FORM GOES BELOW -->
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" name="registerForm">
<table style="width: 100%">
<tr>
<td>User ID</td>
<td><input name="userid" type="text" style="width: 300px" /><br /></td>
</tr>
<tr>
<td>Name</td>
<td><input name="name" type="text" style="width: 300px" /><br /></td>
</tr>
<tr>
<td></td>
<td><input style="width: 130px; height: 30px" type="submit" name="submit" value="Register Now" /><br /></td>
</tr>
</table>
</form>
<?php } ?>
Your script should be like
$getUserId = mysql_query("SELECT id FROM `user` WHERE `userid` = '".$userid."'");
because you are getting all the results and you need to retrive the id only and your form action should be your same page itself
you need to read about mysql queries http://php.net/manual/en/book.mysql.php
also check your insert query not any data values inserted.
<?php if(isset($_POST['submit']))
{
conFunc(); // Connection Function
$userid = $_POST['userid'];
$name = $_POST['name'];
$getUserId = mysql_query("SELECT * FROM user WHERE userid = '".$userid."'");
$id = mysql_fetch_array($getUserId);
if($id)
{
echo "This User ID is Already Available on the System, Please Choose Something Else!";
}
else
{
$query = mysql_query("INSERT INTO user(userid, name) values('" .$userid . "','" . $name . "')";
if($query)
{
echo "A New User is Registered Successfully:<br /><br />";
echo "<b>User ID:</b> " . $userid . "<br />";
echo "<b>User Name:</b> " . $name . "<br />";
}
else
{
echo "There is an Error while Saving: " . mysql_error();
echo "<br />Please click on Create User from menu, and try again<br /><br />.";
}
}
exit;
}
// POST HANDLER -->
?>
<!-- FORM GOES BELOW -->
<form action="" method="post" name="registerForm">
<table style="width: 100%">
<tr>
<td>User ID</td>
<td><input name="userid" type="text" style="width: 300px" /><br /></td>
</tr>
<tr>
<td>Name</td>
<td><input name="name" type="text" style="width: 300px" /><br /></td>
</tr>
<tr>
<td></td>
<td><input style="width: 130px; height: 30px" type="submit" name="submit" value="Register Now" /><br /></td>
</tr>
</table>
</form>