Expanding Rows for Unique Checkboxes - checkbox

I was just recently given a project for my job to write a script that compares two mysql databases and print out information into an html table. Currently, I am trying to insert a checkbox by each individual's name and when selected, rows pertaining to that individual will expand underneath the person's name. I am combining javascript into my script to do this, although I really have no experience is it. The problem I am having is that when any checkbox is selected, all the rows for each individual is expanding instead of the rows pertaining only to the one individual selected.
Here is my code so far:
PHP Code:
<?php
$link = mysql_connect ($server = "harris.lib.fit.edu", $username = "", $password = "") or die(mysql_error());
$db = mysql_select_db ("library-test") or die(mysql_error());
$ids = mysql_query("SELECT * FROM `ifc_studylog`") or die(mysql_error()); //not single quotes (tilda apostrophy)
$x=0;
$n=0;
while($row = mysql_fetch_array( $ids ))
{
$tracksid1[$x] = $row['fitID'];
$checkin[$x] = $row['checkin'];
$checkout[$x] = $row['checkout'];
$n++;
$x++;
}
$names = mysql_query("SELECT * FROM `ifc_users`") or die(mysql_error()); //not single quotes (tilda apostrophy)
$x=0;
while($row = mysql_fetch_array( $names ))
{
$tracksnamefirst[$x] = $row['firstName'];
$tracksnamesecond[$x] = $row['lastname'];
$tracksid2[$x] = $row['fitID'];
$tracksuser[$x] = $row['tracks'];
$x++;
}
$x=0;
foreach($tracksid2 as $comparename)
{
$chk = strval($x);
?>
JS Code:
$(window).load(function() {
$('.varx').click(function() {
$('.text').toggle(this.checked);
});
});​
PHP Code:
<?php
echo '<td><input id = "<?=$chk?>" type="checkbox" class="varx" /></td>';
echo '<td align="center">'.$comparename.'</td>';
echo'<td align="center">'.$tracksnamefirst[$x].'</td>';
echo'<td align="center">'.$tracksnamesecond[$x].'</td>';
$z=0;
foreach($tracksid1 as $compareid)
{
$HH=0;
$MM =0;
$SS =0;
if($compareid == $comparename)// && $tracks==$tracksuser[$x])
{
$SS = sprintf("%02s",(($checkout[$z]-$checkin[$z])%60));
$MM = sprintf("%02s",(($checkout[$z]-$checkin[$z])/60 %60));
$HH = sprintf("%02s",(($checkout[$z]-$checkin[$z])/3600 %24));
// echo'<td align="center">'.$HH.':'.$MM.':'.$SS.'</td>';
echo '</tr>';
echo '<tr>';
echo "<td id='txt' class='text' align='center' colspan='2' style='display:none'></td>";
echo "<td id='txt' class='text' align='center' style='display:none'>".$checkin[$z]."</td>";
echo '</tr>';
}
echo '<tr>';
$z++;
echo '</tr>';
}
$x++;
}
}
?>
Any help is appreciated and apologies if I am too vague on the subject. The username and password have been left out for security reasons.

Related

WPDB exporting custom query to csv - file not being created

I'm using the following code to export a custom MYSQL query to CSV. The data and column headers are working fine (print $csv_output; is exactly as I expect) but the actual CSV file is not being created.
What am I getting wrong?
function generate_csv(){
global $wpdb;
$table_name = $wpdb->prefix."ck_shipment";// table name
$file = 'database_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $table_name",ARRAY_A );
// get column names
$query = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='".$wpdb->dbname."' AND `TABLE_NAME`='".$table_name."'";
$columnNamesList = $wpdb->get_results($query);
foreach ( $columnNamesList as $column_name ) {
$csv_output.=$column_name->COLUMN_NAME.",";
}
// remove last additional comma
$csv_output = substr($csv_output,0,strlen($csv_output)-1);
// start dumping csv rows in new line
$csv_output.="\n";
if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}
$filename = $file."_".date("Y-m-d_H-i",time());
print $csv_output;
exit;
}
?>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<br /><input type="submit" name="export" value="export" class="button-primary">
</form>
<?php
if (isset($_POST['export'])) {
generate_csv();
}
Thanks!

Php keep checkboxes checked after form error

How can i keep the selected checkboxes checked, after the form submit on error? Now, i get this error message: Warning: in_array() expects parameter 2 to be array, string given in
Thanks!
function runsql_array($sql)
{
global $kapcs;
$res = mysqli_query($kapcs , $sql) or die(mysqli_error( $kapcs));
if (mysqli_num_rows($res) == 0)
{
return array();
}
else
{
$out = array();
while ($a = mysqli_fetch_assoc($res))
{
$out[] = $a;
}
return $out;
}
}
<td>
<?php
$ertek = isset($_POST["termek_tul_tipusok"]) ? $_POST["termek_tul_tipusok"] : '' ;
$values = runsql_array("SELECT termek_tipus_id, termek_tipus_nev FROM termek_tipusok WHERE termek_tipus_status = 1
ORDER BY termek_tipus_nev ASC");
foreach($values as $val=>$szoveg)
{
$checked = in_array($val, $ertek) ? ' checked ' : '' ;
echo '<div style="margin:4px 0;"><label style="cursor:pointer;" for="tulajdonsag-'.$val.'">';
echo '<input id="tulajdonsag-'.$val.'" type="checkbox" name="termek_tul_tipusok[]" '.$checked.' value="'.$val.'" />';
echo $szoveg['termek_tipus_nev'];
echo '</label></div>';
}
?>
</td>
the line
$ertek = isset($_POST["termek_tul_tipusok"]) ? $_POST["termek_tul_tipusok"] : '' ;
defines $ertek. And in the case that the post dosnt exist its defined as an empty string. You should use an empty Array.
$ertek = isset($_POST["termek_tul_tipusok"]) ? $_POST["termek_tul_tipusok"] : array() ;

How to insert extracted data between td tags into database?

I am trying to insert extracted data between td tags into database(student_information), however I always got no data in the database. Any help is appreciated! Thanks
$matchcount = preg_match_all('/<div class=\"name\">(.*?)<\/div>/s', $data, $matches);
$hostname = "localhost";
$username = "root";
$password = "baekhyun8100";
$databaseName = "student_information";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$query = "INSERT INTO student_information";
$result = mysqli_query($connect, $query);
if ($matchcount > 0) {
for ($i = 0; $i < $matchcount; $i++) {
echo("\n" . "\n");
#echo($matches[1][$i]);
echo strip_tags($matches[1][$i], '<div>');
mysqli_query($connect, "INSERT INTO `student_information` (`name`) VALUES ('" . strip_tags($matches[1][$i]) . "');");
}
} else {
echo('No matches');
}

How to put a database into an array

I finally succeeded in making an image carousel by using php.
The code below works, but there are no images in it.
Now I am trying to make this array to get data from a Mysql database.
Could you show me an example of how do I do it?
<?php
//MySQL database connection
$mysqli = new mysqli('localhost', 'root', '', 'webshop');
$SQL = "SELECT image FROM productlist LIMIT 5";
$result = $mysqli->query($SQL);
$array = array(
0 => "picture1.jpg",
1 => "picture2.jpg",
2 => "picture3.jpg",
3 => "picture4.jpg",
4 => "picture5.jpg",
5 => "kalle6.jpg",
);
//Goes to previous page when clicking on prev
$index = $_GET['start'];
if ($index > 0) {
echo ' prev ';
} else {
echo ' prev ';
}
//Display 3 images
$show_img = 3;
$num_img = 0;
for($i = $_GET['start']; $i<count($array) && $num_img < $show_img; $i++) {
$num_img++;
echo "<img src=".$array[$i]."/>\n";
}
for($i=$num_img; $i<$show_img;$i++) {
echo "<img src=".(count($array) - 1)."/>\n";
}
//Goes to next page when clicking on next
if ($index < count($array) - 1) {
echo ' next ';
} else {
echo ' next ';
}
?>
You should have a look at this: http://php.net/manual/en/mysqli-result.fetch-array.php
/* numeric array */
/* $row is your $array */
$row = $result->fetch_array(MYSQLI_NUM);
echo "<pre>";
print_r($row);
echo "<pre>";
This should help you get the result you want

Help with pagination

I have created pagination and it is currently working, but the only issue is if I have thousands and thousands of results... the display would be:
[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18] and so on.
I just want the display the page to display to look similar to this:
previous [1][2][3][4][5]... next
previous ...[5][6][7][8][9][10]...next
Can anyone give advice or supply some example code that would give me a result like above? If anything is at all unclear please let me know!
Cheers,
Neil
The code that I am currently using is below:
<?php
/*data base connection */
include "datebase connection";
/* SQL query */
$tsql = (" SELECT TOP 100 tie_parent_id, CAST(geo_post AS varchar(6)) + '.' + CAST(geo_sample AS varchar(6)) AS Mile, gps_lat, gps_long, rotten, split, wheel_cut, broken, quality
FROM database
");
$stmt = sqlsrv_query($conn,$tsql, array(), array( "Scrollable" => 'static'));
if( $stmt === false)
{
echo "Error in query preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
/* DETERMINING THE NUMBER OF ROWS (AND PAGES) */
// Set the number of rows to be returned on a page.
$rowsPerPage = 10;
// Get the total number of rows returned by the query.
$rowsReturned = sqlsrv_num_rows($stmt);
if($rowsReturned === false)
die( print_r( sqlsrv_errors(), true));
elseif($rowsReturned == 0)
{
echo "No rows returned.";
exit();
}
else
{
/* Calculate number of pages. */
$numOfPages = ceil($rowsReturned/$rowsPerPage);
}
/* FUNCTION FOR PAGING */
function getPage($stmt, $pageNum, $rowsPerPage )
{
$offset = ($pageNum - 1) * $rowsPerPage;
$rows = array();
$i = 0;
while($row = sqlsrv_fetch_array($stmt,
SQLSRV_FETCH_NUMERIC,
SQLSRV_SCROLL_ABSOLUTE,
$offset + $i)
&& $i < $rowsPerPage)
{
array_push($rows, $row);
$i++;
}
$row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_NUMERIC,SQLSRV_SCROLL_ABSOLUTE, $offset -1);
return $rows;
}
// Display the selected page of data.
echo "<table width='800' border='0'>";
echo "<tr> <th>Tie ID</th> <th>Mile/Yard</th> <th>GPS Lat</th><th>GPS Long</th><th>Rotten</th><th>Split</th><th>WheelCut</th> <th>Broken</th><th>Quality</th> </tr>";
// keeps getting the next row until there are no more to get
$pageNum = isset($_GET['pageNum']) ? $_GET['pageNum'] : 1;
$page = getPage($stmt, $pageNum, $rowsPerPage);
$color1 = "#ffffff";
$color2 = "#edf5fa";
$row_count = "0";
while($row_count<10 ) {
$row=sqlsrv_fetch_array($stmt);
$tie_parent_id = $row["tie_parent_id"];
$geo_post = $row["Mile"];
$lat =$row["gps_lat"];
$long =$row["gps_long"];
$rotten =$row["rotten"];
$split =$row["split"];
$wheelcut =$row["wheel_cut"];
$broken =$row["broken"];
$quality =$row["quality"];
$row_color = ($row_count % 2) ? $color1 : $color2;
?>
<tr>
<td bgcolor="<?php echo $row_color ?>">
<?php echo $row["tie_parent_id"]; ?></td>
<td bgcolor="<?php echo $row_color ?>">
<?php echo $row["Mile"];?> </td>
<td bgcolor="<?php echo $row_color ?>">
<?php echo $row["gps_lat"];?></td>
<td bgcolor="<?php echo $row_color ?>">
<?php echo $row["gps_long"];?></td>
<td bgcolor="<?php echo $row_color ?>">
<?php echo $row["rotten"];?></td>
<td bgcolor="<?php echo $row_color ?>">
<?php echo $row["split"];?></td>
<td bgcolor="<?php echo $row_color ?>">
<?php echo $row["wheel_cut"];?></td>
<td bgcolor="<?php echo $row_color ?>">
<?php echo $row["broken"];?></td>
<td bgcolor="<?php echo $row_color ?>">
<?php echo $row["quality"];?></td>
</td></tr>
<?php
$row_count++;
}
?>
<?php
/* PREVIOUS PAGE NAVIGATION TOP OF PAGE */
// Display Previous Page link if applicable.
if($pageNum > 1)
{
$prevPageLink = "?pageNum=".($pageNum - 1);
echo "<a href='$prevPageLink'>Previous Page</a>&nbsp";
}
/*DISPLAYING LINKS TO PAGES TOP OF PAGE*/
for($i = 1; $i<=$numOfPages; $i++)
{
$pageLink = "?pageNum=$i";
print("<a href=$pageLink>$i</a> ");
}
/* NEXT PAGE NAVIGATION TOP OF PAGE */
// Display Next Page link if applicable.
if($pageNum < $numOfPages)
{
$nextPageLink = "?pageNum=".($pageNum + 1);
echo " <a href='$nextPageLink'>Next Page</a>";
}
?>
</form>
<?php
/* Close the connection. */
sqlsrv_close( $conn);
?>
The change is actually not too crazy - you have most of it. Your algorithm needs to change just a little bit for the display of the pages - so instead of running your loop like you have:
/*DISPLAYING LINKS TO PAGES TOP OF PAGE*/
for($i = 1; $i<=$numOfPages; $i++)
{
$pageLink = "?pageNum=$i";
print("$i ");
}
You need to start at the current page number that you are on...
/*first check to make sure the number of pages don't exceed maximum*/
$totalPagesToLoop = $pageNum + $numOfPages;
if($totalPagesToLoop > ceiling(total number of pages required to show all the records ([number of total rows]/[number of rows to show per page])
{
$totalPagesToLoop = ceiling(total number of pages required to show all the records ([number of total rows]/[number of rows to show per page]);
}
/*DISPLAYING LINKS TO PAGES TOP OF PAGE*/
for($i = $pageNum; $i<=$totalPagesToLoop; $i++)
{
$pageLink = "?pageNum=$i";
print("$i ");
}
But - thats not all, you will now have to code the special 'previous' and 'next' buttons (you decide how many to increment when you click on that - google increments by 1, until it reaches 20, and then just shows 20 at a time, moving one by one. You'll have to test your variable to decide whether to show the 'previous' or 'next' button at all...
I managed to resolve the issue by using the below code:
for($i = $pageNum; $i<=$numOfPages&&$pagesadded<=9; $i++)
{
$pagesadded+=1;
$pageLink = "?pageNum=$i";
print("<a href=$pageLink>$i</a> ");
}
It displays 10 pages at a time.
Cheers,
Neil

Resources