Old values not appearing when editing PHP MySQL - php

So, I am doing a library system. A librarian can view all the books, and may choose to edit a book and it's details. However, when I click edit, the values do not show up in the input field.
This is my edit portion of the code. I am getting an error:
count(): Parameter must be an array or an object that implements
Countable on line 7
which is if (count($record) == 1 ) {:
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM bookinfo WHERE BookNo='$BookNo'");
if (count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$BookNo = $n['BookNo'];
$ISBN = $n['ISBN'];
$title = $n['title'];
$author = $n['author'];
$publisher = $n['publisher'];
$status = $n['status'];
$cost = $n['cost'];
}
}
?>
This is my displaying of the data for the librarian, along with the edit button:
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['BookNo']; ?></td>
<td><?php echo $row['ISBN']; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['author']; ?></td>
<td><?php echo $row['publisher']; ?></td>
<td><?php echo $row['status']; ?></td>
<td><?php echo $row['cost']; ?></td>
<td>
<a href="viewBook.php?edit=<?php echo $row['BookNo']; ?>" class="edit_btn" >Edit</a>
</td>
Followed by, the fields in which the librarian can edit the details.
<?php
if (isset($_GET['edit'])) { ?>
<form method="post" action = "viewBook.php">
<input type="hidden" name="BookNo" value="<?php echo $BookNo; ?>">
<input type="text" name="ISBN" value="<?php echo $ISBN; ?>">
<input type="text" name="title" value="<?php echo $title; ?>">
<input type="text" name="author" value="<?php echo $author; ?>">
<input type="text" name="publisher" value="<?php echo $publisher; ?>">
<input type="text" name="status" value="<?php echo $status; ?>">
<input type="text" name="cost" value="<?php echo $cost; ?>">
<?php if ($update == true): ?>
<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Save</button>
<?php endif ?>
<?php } ?>
</form>
When I click the edit button, I get the error stated above, as well as the text fields not having the details already written inside.

count() function only works with arrays and other countable fields
use the mysqli_num_rows
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM bookinfo WHERE BookNo='$BookNo'");
if (mysqli_num_rows($record) == 1 ) {
$n = mysqli_fetch_array($record);
$BookNo = $n['BookNo'];
$ISBN = $n['ISBN'];
$title = $n['title'];
$author = $n['author'];
$publisher = $n['publisher'];
$status = $n['status'];
$cost = $n['cost'];
}
}
?>
this mysqli_num_rows can give you result of the count of amount of data from sql query
I think this will work for you.

use mysqli_fetch_assoc()
So, I am doing a library system. A librarian can view all the books, and may choose to edit a book and it's details. However, when I click edit, the values do not show up in the input field.
This is my edit portion of the code. I am getting an error:
count(): Parameter must be an array or an object that implements Countable on line 7
which is if (count($record) == 1 ) {:
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM bookinfo WHERE BookNo='$BookNo'");
if (count($record) == 1 ) {
$n = mysqli_fetch_assoc($record);
$BookNo = $n['BookNo'];
$ISBN = $n['ISBN'];
$title = $n['title'];
$author = $n['author'];
$publisher = $n['publisher'];
$status = $n['status'];
$cost = $n['cost'];
}
}
?>

Related

Old values not appearing in text field when called

I'm trying to call the old values to be edited. What part am I wrong at?
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM bookinfo WHERE BookNo='$BookNo'");
if (mysqli_num_rows($record) == 1 ) {
$n = mysqli_fetch_array($record);
$BookNo = $n['BookNo'];
$ISBN = $n['ISBN'];
$title = $n['title'];
$author = $n['author'];
$publisher = $n['publisher'];
$status = $n['status'];
$cost = $n['cost'];
}
}
?>
<a href="viewBook.php?edit=<?php echo $row['BookNo']; ?>" class="edit_btn" >Edit</a>
</td>
<?php
if (isset($_GET['edit'])) { ?>
<form method="post" action = "viewBook.php">
<input type="hidden" name="BookNo" value="<?php echo $BookNo; ?>">
<input type="text" name="ISBN" value="<?php echo $ISBN; ?>">
<input type="text" name="title" value="<?php echo $title; ?>">
<input type="text" name="author" value="<?php echo $author; ?>">
<input type="text" name="publisher" value="<?php echo $publisher; ?>">
<input type="text" name="status" value="<?php echo $status; ?>">
<input type="text" name="cost" value="<?php echo $cost; ?>">
<?php if ($update == true): ?>
<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Save</button>
<?php endif ?>
<?php } ?>
</form>
So far, what it does is, when the user clicks the edit button, it just shows 6 text fields. I thought by doing what I did, it was supposed to show the details already filled in the textbox.
When you do
$record = mysqli_query($db, "SELECT * FROM bookinfo WHERE BookNo='$BookNo'");
$BookNo is not defined.
maybe you wanted to do something like this:
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM bookinfo WHERE BookNo='$id'");
<form method="post" action = "viewBook.php">
your form method is "post" but you are checking $_GET You must check $_POST
if (isset($_GET['edit']))
you are passing value in $id And using $BookNo which not define.
only 6 input field will be show because first one is using hidden property.
<input type="hidden" name="BookNo" value="<?php echo $BookNo; ?>">
when you click on submit button data will be receive by $_POST

PHP button click - value / id to pass over

Hey I'm currently having a problem with trying to make my input button have a value of the id / server that I need and it showing a different value this is how my code currently looks I know the HTML and forms are invalid I will be refactoring it however I'm trying to get a server identifier and a id identifier to cross to another page
<?php
$propertyType = $xmlDom1->getElementsByTagName('PropertyType');
$rent = $xmlDom1->getElementsByTagName('rates');
$rooms = $xmlDom1->getElementsByTagName('rooms');
//$server = $xmlDom1->getElementsByTagName('server');
$propertyServer = $xmlDom1->getElementsByTagName('Property');
$propertyID = $xmlDom1->getElementsByTagName('Property');
$imageURL = $xmlDom1->getElementsByTagName('url');
$imageAlt = $xmlDom1->getElementsByTagName('altText');
$server = $propertyID->item($i)->getAttribute('server');
echo '<form action="level5Details.php" method="get" enctype="application/x-www-form-urlencoded">';
echo '<table><th>Type:</th><th>Rent:</th><th>Rooms:</th><th>Server</th>';
$records = $xmlDom1->documentElement->childNodes;
for ($i = 0; $i < $records->length; $i++) {
echo "<tr><td>".$propertyType->item($i)->nodeValue."</td>";
echo "<td>".$rent->item($i)->nodeValue."</td>";
echo "<td>".$rooms->item($i)->nodeValue."</td>";
echo "<td>".$propertyServer->item($i)->getAttribute('Server')."</td>";
echo '<td><img src="data:image/jpeg;base64,'.$imageURL->item($i)->nodeValue.'" alt="'.$imageAlt->item($i)->nodeValue.'"></img></td>';
?>
<td>
<button class="submit" type="submit" value="<?php echo $propertyID->item($i)->getAttribute('pid'); ?>" name="submit22">something </button>
</td>
</tr>
<?php
}
?>
</form>
If you are trying to generate lots of form each with just a button then you need to put the form in a table cell like this
It might also be useful to place the data items you want to pass in hidden fields rather than try and put 2 data items in the button value
<?php
$propertyType = $xmlDom1->getElementsByTagName('PropertyType');
$rent = $xmlDom1->getElementsByTagName('rates');
$rooms = $xmlDom1->getElementsByTagName('rooms');
//$server = $xmlDom1->getElementsByTagName('server');
$propertyServer = $xmlDom1->getElementsByTagName('Property');
$propertyID = $xmlDom1->getElementsByTagName('Property');
$imageURL = $xmlDom1->getElementsByTagName('url');
$imageAlt = $xmlDom1->getElementsByTagName('altText');
$server = $propertyID->item($i)->getAttribute('server');
echo '<table><th>Type:</th><th>Rent:</th><th>Rooms:</th><th>Server</th>';
$records = $xmlDom1->documentElement->childNodes;
for ($i = 0; $i < $records->length; $i++) {
echo "<tr><td>".$propertyType->item($i)->nodeValue."</td>";
echo "<td>".$rent->item($i)->nodeValue."</td>";
echo "<td>".$rooms->item($i)->nodeValue."</td>";
echo "<td>".$propertyServer->item($i)->getAttribute('Server')."</td>";
echo '<td><img src="data:image/jpeg;base64,'.$imageURL->item($i)->nodeValue.'" alt="'.$imageAlt->item($i)->nodeValue.'"></img></td>';
$pid = $propertyID->item($i)->getAttribute('pid');
?>
<td>
<form action="level5Details.php" method="get" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="pid" value="<?php echo $pid;?>">
<input type="hidden" name="server" value="<?php echo $server;?>">
<button class="submit" type="submit" value="submit" name="submit22">something</button>
</form>
</td>
</tr>
<?php
}
?>
If you just want the button to carry all the data and have only one form you will have to package the 2 data items into one string and sent it as the value of the button
<?php
$propertyType = $xmlDom1->getElementsByTagName('PropertyType');
$rent = $xmlDom1->getElementsByTagName('rates');
$rooms = $xmlDom1->getElementsByTagName('rooms');
//$server = $xmlDom1->getElementsByTagName('server');
$propertyServer = $xmlDom1->getElementsByTagName('Property');
$propertyID = $xmlDom1->getElementsByTagName('Property');
$imageURL = $xmlDom1->getElementsByTagName('url');
$imageAlt = $xmlDom1->getElementsByTagName('altText');
$server = $propertyID->item($i)->getAttribute('server');
echo '<form action="level5Details.php" method="get" enctype="application/x-www-form-urlencoded">';
echo '<table><th>Type:</th><th>Rent:</th><th>Rooms:</th><th>Server</th>';
$records = $xmlDom1->documentElement->childNodes;
for ($i = 0; $i < $records->length; $i++) {
echo "<tr><td>".$propertyType->item($i)->nodeValue."</td>";
echo "<td>".$rent->item($i)->nodeValue."</td>";
echo "<td>".$rooms->item($i)->nodeValue."</td>";
echo "<td>".$propertyServer->item($i)->getAttribute('Server')."</td>";
echo '<td><img src="data:image/jpeg;base64,'.$imageURL->item($i)->nodeValue.'" alt="'.$imageAlt->item($i)->nodeValue.'"></img></td>';
$dataPackage = $propertyID->item($i)->getAttribute('pid') . ':' . $server;
?>
<td>
<button class="submit" type="submit" value="<?php echo $dataPackage;?>" name="submit22">something</button>
</td>
</tr>
<?php
}
</table>
</form>
?>
Now in the receiving form unpack the data for use
<?php
// usual checks for things existing
list($pid, $server) = explode(':', $_GET['submit22'];

Counter increasing in refresh and in reload in php

I have set a counter in php code to increment the id value in mysql on every next click but when I refresh or reload the page the value is increasing automatically is there any solution for this problem or any other substitute.
<?php
$db = mysqli_connect('localhost','root','root','rahul');
$questions ="";
$msg2 ="";
$o1 ="" ;
$o2 ="" ;
$o3 ="" ;
$o4 ="" ;
$disable = "";
$disable2 = "";
session_start();
if(empty($_SESSION['count']))
$_SESSION['count'] = 0;
if(isset($_POST['sub1'])){
$ans = $_POST['ans'];
$email = "rahul#gmail.com";
$order = $_SESSION['count']+1;
echo $order;
$_SESSION['count'] = $order;
$sql = (" SELECT * FROM qna WHERE id = $order ");
$query = mysqli_query($db, $sql);
$row=mysqli_fetch_array($query, MYSQLI_ASSOC);
$questions = $row['questions'];
$o1 = $row['o1'];
$o2 = $row['o2'];
$o3 = $row['o3'];
$o4 = $row['o4'];
$disable="";
if($_SESSION['count']>5)
{
$disable = "disabled";
}
$disable2 = "";
if($_SESSION['count']<=1)
{
$disable2 = "disabled";
}
//$sql2 = "INSERT INTO result (id, answer, email) VALUES ('', '$ans', '$email') ".mysqli_error();
/*
$sql3 = mysqli_query($db, "INSERT INTO result (answer, email) VALUES ('$ans', '$email')");
if(mysqli_affected_rows($sql3)== true)
{
echo "inserted";
}
else
{
echo "not inserted";
}
*/
echo $ans. $email;
}
$sql4 = mysqli_query("select * from result");
$row = mysqli_fetch_array($db, $sql4);
// while()
echo $row['id'];
for($i=1;$i<=5;$i++)
{
}
?>
<?php
if(isset($_POST['sub2'])){
$result2 = $_SESSION['count']-1;
$_SESSION['count'] = $result2;
$sql = (" SELECT * FROM qna WHERE id = $result2 ");
$query = mysqli_query($db, $sql);
$row=mysqli_fetch_array($query, MYSQLI_ASSOC);
$questions = $row['questions'];
$o1 = $row['o1'];
$o2 = $row['o2'];
$o3 = $row['o3'];
$o4 = $row['o4'];
if($_SESSION['count']<=1){
$disable2 = "disabled";
}
}
session_write_close();
?>
<?php
if(isset($_POST['start'])){
$order = $_SESSION['count']+1;
echo $order;
$_SESSION['count'] = $order;
$sql = (" SELECT * FROM qna WHERE id = 1 ");
$query = mysqli_query($db, $sql);
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$questions = $row['questions'];
$o1 = $row['o1'];
$o2 = $row['o2'];
$o3 = $row['o3'];
$o4 = $row['o4'];
$disable="";
if($_SESSION['count']>=5)
{
$disable = "disabled";
}
$disable2 = "";
if($_SESSION['count']<=1){
$disable2 = "disabled";
}
session_write_close();
}
?>
<center><br><br><br>
<form method="post">
<input type="submit" name="start" value="start">
</form>
Log out
<form action="" method="post" >
<table border="1" height="300px" width="500px">
<tr>
<th colspan="2"><?php echo $questions; ?></th>
</tr>
<tr>
<td><input type="radio" name="ans" id="ans" value="<?php echo $o1; ?>"><?php echo $o1; ?></td>
<td><input type="radio" name="ans" value="<?php echo $o2; ?>"><?php echo $o2; ?></td>
</tr>
<tr>
<td><input type="radio" name="ans" value="<?php echo $o3; ?>"><?php echo $o3; ?></td>
<td><input type="radio" name="ans" value="<?php echo $o4; ?>"><?php echo $o4; ?></td>
</tr>
<tr colspan="2">
<td><center><input type="submit" name="sub1" value="next" <?php echo $disable ?>> </td>
<td><center><input type="submit" name="sub2" value="previous" <?php echo $disable2 ?>>
<input type="submit" name="submit3" value="submit" > </td>
</tr>
</form>
</table>
<?php
if(isset($_POST['submit3']))
{
$ans = $_POST['ans'];
$email = "dummy";
//$sql2 = "INSERT INTO result (id, answer, email) VALUES ('', '$ans', '$email') ".mysqli_error();
$sql3 = mysqli_query($db, "INSERT INTO result (answer, email) VALUES ('$ans', '$email')");
if(mysqli_affected_rows($sql3)== true)
{
echo "inserted";
}
else
{
echo "not inserted";
}
echo $ans. $email;
}
?>
when you are reloading a web-page, you are reloading its POST (and also GET) data as well if it's there. if you are submitting a form then the target page contains POST data in its header. so if you reload this page it's like you would have clicked the button again.
since you are already using a session there is a workaround:
add a hidden field with a micro-timestamp in your form. this micro-timestamp will be different every time your page gets loaded (per user) - but this "new" timestamp only get's posted when you use the button. when you just refresh the page, you are reloading with the old timestamp.
so you just need to save compare the last timestamp (saved in a session variable) with the currently posted timestamp. if they are equal - the page just got refreshed - if they are not equal, then you got a new timestamp which was sent by your form:
<?php
session_start();
if(!isset($_SESSION["timestamp"]))
$_SESSION["timestamp"] = 0;
if(!isset($_POST["timestamp"]))
$_POST["timestamp"] = 0;
// previous timestamp - saved in session variable:
$prev_ts = $_SESSION["timestamp"];
// currently posted timestamp:
$post_ts = $_POST["timestamp"];
if($prev_ts != $post_ts)
{
// code to increase your counter goes here.
$feedback = "button pressed";
}
else
{
// do nothing when the page just got refreshed
$feedback = "refreshed";
}
$_SESSION["timestamp"] = $post_ts;
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php echo $feedback; ?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
<input type="hidden" name="timestamp" value="<?php echo microtime(); ?>">
<input type="submit" name="go" value="count">
</form>
</body>
</html>

Checkboxes are not updating in the database

I've got a question about databases and checkboxes. I've got a table looking like:
Website is looking like:
At the bottom of the page I also have a button, so when I submit the checked checkboxes will be updated to 1 or 0 in the database. (True or false)
So when I click on the 3rd checkbox under trained, it will update the trained column in the database with a user/room id of '3583'. (ID is shown right of the screen)
Code:
<form class='verwerkInfo' method='post' action='<?php echo $_SERVER['PHP_SELF']; ?>?license=6'>
<td>
<?php if($room->trained == 1) { ?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked> <?php echo "Y"; } else{ ?> <input type='checkbox' name="<?php echo $room->room_id; ?>"> <?php echo "N"; }?> </td>
<Td><?php if($room->active == 1) { ?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked> <?php echo "Active"; } else { ?> <input type='checkbox' name="<?php echo $room->room_id; ?>" <?php echo "Inactive"; } ?>
</td>
<Td><?php echo $room->configuration; ?></td>
<td><?php echo $room->room_id; ?></td>
<td><?php var_dump($room->user_id); }?></td>
</tr>
So I guess I have a problem in the names of the checkboxes.
The query is looking like:
$trainedQuery = "UPDATE room_users
SET trained = 1
WHERE user_id = $room->user_id";
The $room->user_id is referring to the user_id in the database.
Here's a way to give the checkboxes unique names and pass extra information with each element:
name="trained[<?php echo $room->room_id; ?>]" value="<?php echo $room->user_id; ?>"
Then in the PHP script that processes the form submission you can:
foreach ( $_POST['trained'] as $room_id => $user_id ) {
// This query needs protection from SQL Injection!
$trainedQuery = "UPDATE room_users SET trained = 1 WHERE user_id = $user_id";
}
It's not clear what the relationship is between room_id and user_id and why you're updating the room_user table with only user_id. What do you do with the room_id?
Is this what you actually need:
// This query needs protection from SQL Injection!
$trainedClear = "UPDATE room_users SET trained = 0 WHERE user_id = $user_id";
$db->exec($trainedClear); // first clear all
foreach ( $_POST['trained'] as $room_id => $user_id ) {
// This query needs protection from SQL Injection!
$trainedQuery = "UPDATE room_users SET trained = 1
WHERE user_id = $user_id AND room_id = $room_id";
$db->exec($trainedQuery); // then add selections
}
// assuming there's a database connection `$db-exec`.
// Replace with your actual connection and query method.
Refactored checkbox columns for clarity:
<?php
$room_id = $room->id;
$room_configuration = $room->configuration;
$room_user_id = $room->user_id;
if ( $room->trained == 1 ) {
$trained_checked = 'checked';
$trained_label = 'Y';
}
else {
$trained_checked = '';
$trained_label = 'N';
}
if ( $room->active == 1 ) {
$active_checked = 'checked';
$active_label = 'Active';
}
else {
$active_checked = '';
$active_label = 'Inactive';
}
echo <<<EOT
<td><input type="checkbox" name="trained[$room_id]" value="$room_user_id" $trained_checked> $trained_label</td>
<td><input type="checkbox" name="active[$room_id]" value="$room_user_id" $active_checked> $active_label</td>
<td>$room_configuration</td>
<td>$room_id</td>
<td>$room_user_id</td>
EOT;
?>
Just change the checkbox names attribute with adding yes,no and active
name="yes_<?php echo $room->room_id; ?>"
name="no_<?php echo $room->room_id; ?>"
name="act_<?php echo $room->room_id; ?>"

undefined offset error

I want to display values retrieved from mysql in forms and in row by row format.
So i used the following code.
<?php
while($rows1 = mysql_fetch_array($result1)){
?>
<tr height="30" >
<?php $elyid = $rows1['id'] ?>
<form action="leaveactions.php" method="post" name="viewleave">
<td width="82"><?php echo $rows1['empid'];?></td>
<td><?php echo $rows1['name'];?></td>
<td><?php echo $rows1['leavetype'];?></td>
<td width="82"><?php echo $rows1['startdate']; ?></td>
<td width="82"><?php echo $rows1['enddate']; ?></td>
<td><?php echo $rows1['leavetype']; ?></td>
<td>
<input type="submit" name="<?php $rows1['id']; ?>" value="accept"/>
</td>
<td>
<input type="submit" name="reject" value="reject"/>
<input type="hidden" name="emplid" value="<?php echo $rows1['id'] ?>"/>
</td>
</tr>
<?php } ?>
and in leaveactions.php
$ii=0;
$query1 = "select * from applied_leaves where supervisorid ='".$employeeId."' and status='not approved'";
$result1 = mysql_query($query1) or die (mysql_error());
$num1 = mysql_numrows($result1);
while($rows1 = mysql_fetch_array($result1)) {
$ii++;
echo $_POST["$ii"];
if(isset($_POST['$ii'])){
echo "accepted "; echo $_POST['$ii'];
$updateEmp = "update applied_leaves set status='".$accept."' where id='$ii' " ;
$uresult = mysql_query($updateEmp) or die (mysql_error());
if($uresult != null){
echo "Assignment Added successfully<br>";
?>
View Added Details
<?php
} else {
echo "error";
}
}
}
?>
but when run i get
Notice: Undefined offset: 1
Notice: Undefined offset: 2
.
.
.
.
.
.
like that.
Please help me solving the problem.
Thanks in Advance
EDIT
the new code that is causing exception is
$iii=0;
while($rows1 = mysql_fetch_array($result1))
{
$iii++;
if( $_POST["accpt".$iii] ) {
echo "accepted ";
$updateEmp = "update applied_leaves set status='".$accept."' where id='$iii' " ;
$uresult = mysql_query($updateEmp) or die (mysql_error());
if($uresult != null){
echo "Assignment Added successfully<br>";
?>
View Added Details
<?php break;
}
}
}
I think your main error lies here:
<input type="submit" name="<?php $rows1['id']; ?>" value="accept"/>
Here you do not echo $rows1['id'], so if you have a look in the generated code, the name should be empty.
Correct this to
<input type="submit" name="<?php echo $rows1['id']; ?>" value="accept"/>
Furthermore in leaveactions.php you have the following code:
// ...
echo $_POST["$ii"];
if(isset($_POST['$ii'])){
echo "accepted "; echo $_POST['$ii'];
// ...
Here you should first check, whether the variable (here it is $_POST[$ii] - no " needed) before doing the output.
As a result of the previous error, $_POST[$ii] is not set, thus you get the notice on the first echo and never enter the if-clause afterward.
It's because the array position you are trying to access is empty(not available). Check whether the array position exist using isset method.
if( isset( $array['position'] )
{
//position exists
}
Just don't post your code here. Paste the line which is relevant to the error. At least try commenting the line where the error occurs.

Categories