PHP array is not saving two last elements - php

I'm trying to copy from one array to another but only unique values. I use for loop and when I debug all 10 blues are shown but after for loop the last 2 values are gone.
I debug each array element during the "for loop" and it seems fine coz I see all 10 elements. The problem starts after the for loop. E.g. If I want to print the 9th element it doesn't print it, i.e. it shows emty.
What can be the proble?
P.S> I've tried array_unique(), same output so its not it.
Here is my code:
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE); //to remove annoying notices
include 'connectDB.php';
$queryISBN = mysql_query("SELECT * FROM booksread");
$numrows = mysql_num_rows($queryISBN);
if($numrows!=0)
{
$isbn_array = array();
while($row = mysql_fetch_assoc($queryISBN))
{
$isbn_array[]=$row['ISBN'];
}
$isbn_unique = array();
for ($i=0;$i<count($isbn_array );$i++)
{
if(!in_array($isbn_array[$i],$isbn_unique ))
{
$isbn_unique[$i]=$isbn_array[$i];
echo $isbn_unique[$i]." ---- ";
}
}
}
echo "<h1>Select books you would like to view</h1>";
$submit = $_POST['submit'];
if(isset($_POST['selectedbooks']))
{
$checked = $_POST['selectedbooks'];
}
if($submit)
{
if(!isset($checked))
{
echo "You must check at least one book.";
}
else
{
$_SESSION['checked'] = $checked;
header("location: view_entries_results.php");
}
}
?>
<html>
<body>
<form action="view_entries.php" method="POST">
<table>
<table border="1">
<th>ISBN<th>Title<th>Author<th>Select</th>
<?php
echo "Arr size: ".count($isbn_unique )." </br>";
echo "8: ".$isbn_unique[7]."</br>";
for ($j=0;$j<count($isbn_unique );$j++)
{
$curElement = $isbn_unique[$j];
echo "Cur el: ".$curElement;
$queryBook = mysql_query("SELECT * from book WHERE ISBN='$curElement'");
while ($row = mysql_fetch_assoc($queryBook))
{
$ISBN = $row['ISBN'];
$title = $row['Title'];
$author = $row['Authorname'];
}
?>
<tr>
<td><?php echo $ISBN; ?></td>
<td><?php echo $title; ?></td>
<td><?php echo $author; ?></td>
<td><input type="checkbox" name="selectedbooks[]" value="<?php echo $ISBN; ?>"/>
</tr>
<?php } ?>
</table>
<p><input type="submit" name="submit" value="Add Entry" /></p>
</form>
</body>
</html>

I think
if(!in_array($isbn_array[$i],$isbn_unique ))
{
$isbn_unique[$i] = $isbn_array[$i];
echo $isbn_unique[$i]." ---- ";
}
should be
if(!in_array($isbn_array[$i],$isbn_unique ))
{
$isbn_unique[] = $isbn_array[$i];
echo $isbn_array[$i]." ---- ";
}

I think you have duplicate values in $isbn_array, so its skip keys as its already in array and hence size of $isbn_unique is different then then the $isbn_array. Try to debug on that.

Related

How to show $classname only once

I am trying to echo $classname only once.
So it shows like this for example.
Puppy Dog
1st blah blah
2nd whoever
3rd extra
at present it shows like:
Puppy Dog
1st blah blah
Puppy Dog
2nd whoever
Puppy Dog
3rd extra
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT c.* , p.* FROM result c,dogs p WHERE c.dog_id=p.dog_id";
$result = mysqli_query($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ". mysqli_error
($connection), E_USER_ERROR);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$placement = $row['placement'];
$classname = $row['class_name'];
$dog_name = $row['dog_name'];
$award = $row['award'];
?>
<table>
<tr>
<td><strong><?php echo $classname ?></strong> </td><br>
</tr>
<tr>
<td><strong><?php echo $placement, $award ?></strong> <?php echo $dog_name ?></td>
</tr>
</table>
<?php }}} ?>
Use counter to check if it is already displayed:
$ctr = 0;
while{
$classname = $row['class_name'];
if($ctr == 0){
echo $classname;
$ctr++;
}
//display the rest
...
}
So, don't know why are you using <table> inside the while loop, this will print as per your no's of rows.
Here is the basic example, you can store the values in an array than use it with your HTML:
Example:
<?php
if ($result) {
$myarr = array();
while ($row = mysqli_fetch_assoc($result)) {
$myarr[$row['class_name']][] = $row; //store values into an array against each class in group
}
}
foreach ($myarr as $key => $value) {
echo "Class Name: ". $key."<br/>"; // will print class name
foreach ($value as $fvalue) {
echo "Placement: ".$row['placement']."<br/>";; // placement
echo "Dog Name: ".$row['dog_name']."<br/>"; // dog name
echo "Award: ".$row['award']."<br/>";; // award
}
}
?>
Other solution is using incremental variable in while loop as mentioned in other answers.
You can keep track record by index in while loop like :
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT c.* , p.* FROM result c,dogs p WHERE c.dog_id=p.dog_id";
$result = mysqli_query($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ". mysqli_error
($connection), E_USER_ERROR);
if ($result) {
$i = 1;
while ($row = mysqli_fetch_assoc($result)) {
$placement = $row['placement'];
$classname = $row['class_name'];
$dog_name = $row['dog_name'];
$award = $row['award'];
?>
<table>
<tr>
<td><strong><?php if($i==1) { echo $classname; } ?></strong> </td><br>
</tr>
<tr>
<td><strong><?php echo $placement, $award ?></strong> <?php echo $dog_name ?></td>
</tr>
</table>
<?php $i++; }}} ?>
The Opening and Closing <Table> Tags should be outside your Loop if you expect to have just one Table. Even the <tr> Tags should encompass the <td> Tags if you wish to have rows containing 2 Cells like the Code below shows:
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT c.* , p.* FROM result c,dogs p WHERE c.dog_id=p.dog_id";
$result = mysqli_query ($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ".
mysqli_error($connection), E_USER_ERROR);
?>
<table>
<?php
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$placement = $row['placement'];
$classname = $row['class_name'];
$dog_name = $row['dog_name'];
$award = $row['award'];
?>
<tr>
<td>
<strong><?php echo $classname ?></strong>
<!-- DO YOU NEED THIS <BR>TAG HERE? <br> -->
</td>
<td>
<strong><?php echo $placement, $award ?></strong><?php echo $dog_name ?>
</td>
</tr>
<!-- EXCEPT IF YOU WISH TO HAVE ONE COLUMN, THE ROW BELOW IS UNNECESSARY -->
<!--
<tr>
<td>
<strong><?php echo $placement, $award ?></strong> <?php echo $dog_name ?>
</td>
</tr>
-->
<?php
} // CLOSE THE WHILE LOOP;
} // CLOSE THE IF STATMENT;
?>
</table>

php dynamic pagination logical error

I am developing a page where a user can enter the limit of the table in pagination. While I am doing this the data I enter is taken and query is performed according to that. But as I click on another page of that table the value is reset to default which I set to 5 here.
<?php session_start(); ?>
Submit New record<br><br>
<form method="post">
<input type="text" name="dlimit">
<input type="submit" name="submit">
</form>
<?php
$database = 'test';
require 'connection.php';
if(!isset($_POST['submit']))
{
$limit = 5;
}
else
{
$dlimit = $_POST['dlimit'];
$limit = $dlimit;
}
#$id = $_GET['id'];
if($id==""||$id==null)
{
$page=0;
}
else
{
$page = ($id*$limit)-$limit;
}
$qq ="select * from record limit $page,$limit";
$result = $link -> query($qq);
?>
<table border="1"><th>ID</th>
<th>Name</th>
<th>qualification</th>
<th>address</th>
</tr>
<?php
while ($row = mysqli_fetch_object($result))
{
?>
<tr>
<td><?php echo $row->id ?></td>
<td><?php echo $row->user_name ?></td>
<td><?php echo $row->qualification ?></td>
<td><?php echo $row->address ?></td>
</tr>
<?php
}
?>
</table>
<?php
$query = "SELECT * FROM record";
$result = $link -> query($query);
$rows = mysqli_num_rows($result);
$rr = $rows/$limit;
$rr = ceil($rr);
for ($i=1; $i<=$rr ; $i++) {
?>
<?php echo #$i;?>
<?php
}
mysqli_close($link)
?>
Run the above code and check. If my words are not clear to you.
I think that the $_POST data is missing. You click on the link, so the new page will open without POST infos.
You can change this, if you switch to GET instead of POST. You can add the GET parameter to your <a href=""> Tag.
For example
<a href="pagination.php?page=5&dlimit=100
Also try to avoid the #error suppression and don't pass the $_POST/$_GET Vars directly to your sql string. Bad people could use it for SQL Injections
So I got the answer for my question. I am posting it here if anyone need it on later basis.
Submit New record<br><br>
<form method="get">
<input type="text" name="dlimit">
<input type="submit" name="submit">
</form>
<?php
$database = 'test';
require 'connection.php';
if(empty($_GET['dlimit']) && !isset($_GET['submit']) && empty($_GET['n']))
{
$limit = 5;
global $limit;
}
else
{
if (isset($_GET['dlimit']))
{
$limit = $_GET['dlimit'];
}
else
{
#$limit = $_GET['n'];
}
global $limit;
}
if(!isset($_GET['submit'])&& empty($_GET['n']))
{
$n=5;
global $n;
}
else
{
if(empty($_GET['dlimit']))
{
$n=$_GET['n'];
}
else
{
$n=$_GET['dlimit'];
}
global $n;
}
#$id = $_GET['id'];
if($id==""||$id==null)
{
$page=0;
}
else
{
$page = ($id*$limit)-$limit;
}
$qq ="select * from record limit $page,$limit";
$result = $link -> query($qq);
?>
<table border="1"><th>ID</th>
<th>Name</th>
<th>qualification</th>
<th>address</th>
</tr>
<?php
while ($row = mysqli_fetch_object($result))
{
?>
<tr>
<td><?php echo $row->id ?></td>
<td><?php echo $row->user_name ?></td>
<td><?php echo $row->qualification ?></td>
<td><?php echo $row->address ?></td>
</tr>
<?php
}
?>
</table>
<?php
if (!isset($_GET['submit']) && empty($_GET['n'])) {
$n = 5;
global $n;
}
else
{
if (empty($_GET['dlimit'])) {
$n = $_GET['n'];
}
else
{
$n = $_GET['dlimit'];
}
global $n;
}
$query = "SELECT * FROM record";
$result = $link -> query($query);
$rows = mysqli_num_rows($result);
$rr = $rows/$limit;
$rr = ceil($rr);
for ($i=1; $i<=$rr ; $i++) {
?>
<?php echo #$i;?>
<?php
}
mysqli_close($link)
?>
Again I am mentioning here that files which I included here are just connection where I filled my connection details and other is my record entry file where data is entered by the user.

inserting array using button php

hey guys i've been trying to insert an bunch of data from array and variable into database using button , but it can't be inserted and the database still empty , is there anyone who know where is my mistake ?
here is my code
<?php
include 'koneksi.php';
$arr_nf = array(1,0.334,-0.334,-1);
$arr_ef = array(0,0.333,0.667,1);
$arr_lf = array(1,0.667,0.333,0);
$kelas = "80 keatas" ;
$iduser = "8" ;
$query = mysql_query(" select id_alternatif from tb_alternatif where kelas = '".$kelas."' order by nama "); // run query
$idalter = array();
while($row = mysql_fetch_assoc($query)){
$idalter[] = $row;
}
////////////////////////////////////////// RANGKING LF
foreach ($arr_lf as $val){ // net flow kali 1000
$arr_lfx[]= $val * 1000 ;
}
$int_lfx = array_map( // rubah jd integer
function($value) { return (int)$value; },
$arr_lfx );
$lfx_copy = $int_lfx;
rsort($lfx_copy);
$lfx_copy = array_flip($lfx_copy);
foreach($int_lfx as $val){
$rangkinglf[] = ($lfx_copy[$val]+1);
}
//////////////////////////////////////////
$jumlah_atlet = count($arr_nf);
if (isset($_POST['submit'])){
for($x=0; $x<$jumlah_atlet ;$x++){
mysql_query(" INSERT INTO tb_histori(id_histori, id_user, id_alternatif, kelas, nilai, rangking, waktu) values(NULL, '$iduser', '".$idalter[$x]['id_alternatif']."', '$kelas', '$arr_nf[$x]', '$rangkingnf[$x]', now());") or die(mysql_error()); };
};
print_r($jumlah_atlet);
?>
<html>
<head>
<title> insert data array using only button </title>
</head>
<body>
<form action="" method="post">
<input name="submit" type="button" value="Print & Save" onClick="" />
</form>
</body>
<?php
$data = mysql_query("select * from tb_histori");
$no = 1;
while($d = mysql_fetch_array($data)){
?>
<tr>
<td><?php echo $no++; ?></td>
<td><?php echo $d['id_user']; ?></td>
<td><?php echo $d['id_alternatif']; ?></td>
<td><?php echo $d['kelas']; ?></td>
<td><?php echo $d['nilai']; ?></td>
<td><?php echo $d['rangking']; ?></td>
<td><?php echo $d['waktu']; ?></td>
</tr>
<br>
<?php } ?>
<br>
</html>

Displaying Reminders page from MySQL Database

I've created a PHP program for adding and viewing reminders. The add page works, but I'm having some trouble displaying them properly. How should I code this to only get the actual data? Also, how could I put this into an HTML table? (i.e. column for name, description, and date; rows are the retrieved data)
Thanks
When I open the file in my browser I get this as an output:
Array ( [reminderID] => 14 [reminderName] => Test [reminderDescript] => Test_Descript [reminderDate] => 2012 05 7 )
Code:
<?php include 'header.php'; ?>
<?php include 'database.php'; ?>
<div id="content">
<h1>Reminder List</h1>
<table align ="center">
<thead>
<tr>
<td>Name</td>
<td>Description</td>
<td>Date</td>
</tr>
</thead>
<?php
$query = 'SELECT * FROM reminder_event';
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
print_r($row);
}
?>
</table>
<p><a href='reminder_add.php'>Add Reminder</a></p>
</div>
<?php include 'footer.php'; ?>
print_r() is a diagnostic tool for debugging, not to be used for real output. Instead, output HTML to a table using the array keys fetched from your row.
// Open a table
echo "<table>";
while($row = mysql_fetch_assoc($result)) {
// Output each row
echo "<tr>
<td>{$row['reminderName']}</td>
<td>{$row['reminderDescript']}</td>
<td>{$row['reminderDate']}</td>
</tr>";
}
// Close the table
echo "</table>";
Better still, escape each of the values for HTML output with [htmlspecialchars()] (http://us3.php.net/manual/en/function.htmlspecialchars.php) before output to prevent cross-site scripting attacks and broken HTML if characters like < > & are encountered in the values.
echo "<table>";
while($row = mysql_fetch_assoc($result)) {
// Encode all values for HTML output
$name = htmlspecialchars($row['reminderName']);
$desc = htmlspecialchars($row['reminderDescript']);
$date = htmlspecialchars($row['reminderDate']);
// Then output the encoded values
echo "<tr><td>$name</td><td>$desc</td><td>$date</td></tr>";
}
echo "</table>";
Change:
while($row = mysql_fetch_assoc($result)) {
print_r($row);
}
To:
while($row = mysql_fetch_assoc($result)) {
echo $row['reminderID'];
echo $row['reminderName'];
echo $row['reminderDescript'];
echo $row['reminderDate'];
}
You can echo those values out in whatever HTML you'd like. So, for example, if you want it in a table you would do something like this:
echo "<table><tr>";
while($row = mysql_fetch_assoc($result)) {
echo "<td>" . $row['reminderID'] . "</td>";
echo "<td>" . $row['reminderName'] . "</td>";
echo "<td>" . $row['reminderDescript'] . "</td>";
echo "<td>" . $row['reminderDate'] . "</td>";
}
echo "</tr></table>";
You can clean that up a bit to take some (or all) of the HTML out of the PHP.
<?php include 'header.php'; ?>
<?php include 'database.php'; ?>
<div id="content">
<h1>Reminder List</h1>
<table>
<thead><tr><td>id</td><td>name</td><td>description</td><td>date</td></tr></thead>
<tbody>
<?php
$query = 'SELECT * FROM reminder_event';
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row['reminderID']; ?></td>
<td><?php echo $row['reminderName']; ?></td>
<td><?php echo $row['reminderDescript']; ?></td>
<td><?php echo $row['reminderDate']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<p><a href='reminder_add.php'>Add Reminder</a></p>
</div>
<?php include 'footer.php'; ?>

Show all rows in mysql table then give option to delete specific ones

I want to have the ability to show all the entries in a database table and by each one give the user the ability to delete specific ones.
I am currently using a for each loop that loops through the database showcasing each entry.
$result = mysql_query("SELECT * FROM KeepScores");
$fields_num = mysql_num_fields($result);
echo "<table><tr>";
// printing table headers
echo "<td>Recent Posts</td>";
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
How would to add a delete button that appears by each one and removes the entry from the database table?
You can do it with forms:
//main.php
<?php $result = mysql_query("SELECT * FROM KeepScores"); ?>
<table>
<tr>
<td>Recent Posts</td>
</tr>
<?php while($row = mysql_fetch_array($result)) : ?>
<tr>
<td><?php echo $row['field1']; ?></td>
<td><?php echo $row['field2']; ?></td>
<!-- and so on -->
<td>
<form action="delete.php" method="post">
<input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endwhile; ?>
</table>
//delete.php:
<?php
if(isset($_POST['delete_id'] && !empty($_POST['delete_id']))) {
$delete_id = mysql_real_escape_string($_POST['delete_id']);
mysql_query("DELETE FROM KeepScores WHERE `id`=".$delete_id);
header('Location: main.php');
}
Or you can do it with jQuery and AJAX:
//main.php
<?php $result = mysql_query("SELECT * FROM KeepScores"); ?>
<table>
<tr>
<td>Recent Posts</td>
</tr>
<?php while($row = mysql_fetch_array($result)) : ?>
<tr id="<?php echo $row['id']; ?>">
<td><?php echo $row['field1']; ?></td>
<td><?php echo $row['field2']; ?></td>
<!-- and so on -->
<td>
<button class="del_btn" rel="<?php echo $row['id']; ?>">Delete</button>
</td>
</tr>
<?php endwhile; ?>
</table>
<script>
$(document).ready(function(){
$('.del_btn').click(function(){
var del_id = $(this).attr('rel');
$.post('delete.php', {delete_id:del_id}, function(data) {
if(data == 'true') {
$('#'+del_id).remove();
} else {
alert('Could not delete!');
}
});
});
});
</script>
//delete.php
<?php
if(isset($_POST['delete_id'] && !empty($_POST['delete_id']))) {
$delete_id = mysql_real_escape_string($_POST['delete_id']);
$result = mysql_query("DELETE FROM KeepScores WHERE `id`=".$delete_id);
if($result !== false) {
echo 'true';
}
}
It's all untested and sure needs some adjustment for your specific project, but I think you get the idea and I hope it helps.
Next time, please post your schema if you ask stuff about database.
I thought I would improve on this a little bit by wrapping the delete post in a class and function. I was having the same problem. and this worked great for me. Thanks again # Quasdunk
<?php
// Class to hold the remove post function
class someClass{
//Function for removing the post
function removePost(){
if(isset($_POST['delete_id']) && (!empty($_POST['delete_id']))) {
$delete_id = mysql_real_escape_string($_POST['delete_id']);
$result = mysql_query("DELETE FROM post WHERE post_id='".$delete_id."' AND post_member='" . $_SESSION['SESS_USER'] . "'");
if($result !== false) {
echo 'true';
}
}
}
}
if(isset($_SESSION['SESS_MEMBER_ID'])){
$member = $_SESSION['SESS_USER'];
$res = mysql_query("SELECT * FROM post WHERE post_member='$member' ORDER BY timestamp DESC") or die(mysql_error());
$i = new someClass;
while($row = mysql_fetch_array($res)){
echo '<div style="width:100%;margin:0 auto;border-top:thin solid #000;">';
echo '<div style="width:600px;margin:0 auto;padding:20px;">';
echo $row['post_text'] . '<br>';
$postID = $row['post_id'];
echo '<div style="border-top:thin solid #000;padding:10px;margin-top:5px;background-color:#CCC;">';
echo 'You posted this on: ' . $row['post_date'] . '#' . $row['post_time'];
echo '<div style="float:right;">
<form method="post" action="'. $i->removePost() .'">
<input type="hidden" name="delete_id" value="'.$row['post_id'].'" >
<input type="submit" value="Delete Post">
</form>
</div>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
Produce a key to each table, using jquery,then link it to a php file which an accept the key and delete from the specific table (which also can be passed through jquery)

Categories