I have been struggling trying to find a way to split the records I have into two columns using a prepared statement and was wondering if any could provide assistance
Split Records
<?PHP
$DB_NAME = '';
$DB_HOST = '';
$DB_USER = '';
$DB_PASS = '';
try {
$dsn = "mysql:host=$DB_HOST;dbname=$DB_NAME";
$db = new PDO($dsn, $DB_USER, $DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM `snippets` ORDER BY _ID ASC"; // Split in half here
$prep = $db->prepare($query);
$prep->execute();
echo ' <div class="row">' . "\n"; // Display 1st half here
echo ' <div class="large-12 columns">' . "\n";
echo ' <div class="panel">' . "\n";
while ($row = $prep->fetch()) {
echo ' <div class="row">' . "\n";
echo ' <div class="large-12 columns">' . "\n";
echo ' <b>' . $row['CODE_NAME'] . '</b><br/><br/>' . "\n";
$timestamp = strtotime($row['CODE_TIMESTAMP']);
echo ' Date: ' . date("M d, Y h:m:s A", $timestamp).'<br/><br/>' . "\n";
echo ' </div>' . "\n";
echo ' </div>' . '<br/>' . "\n";
}
$db = null;
}
catch (PDOException $e) {
echo '<div class="row">';
echo '<div class="panel">';
echo 'Connection failed: ' . $e->getMessage();
echo '</div>';
echo '</div>';
}
echo ' </div>' . "\n";
echo ' </div>' . "\n";
echo ' </div>' . "\n";
// Create a 2nd column here to display second half
?>
I would like to correctly calculate the total number of records and then split it in half and display on half in one column and the other in another which I have figured out I just can't seem to get the records split and then displayed
I managed to get it working by doing the following
<!DOCTYPE html>
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<html>
<?php $title = 'ALL'; $page = 'all';include 'includes/header.php';?>
<body>
<?php include 'includes/nav.php'; ?>
<div class="row">
<div class="small-6 small columns">
<?php
$DB_NAME = '';
$DB_HOST = '';
$DB_USER = '';
$DB_PASS = '';
try {
$dsn = "mysql:host=$DB_HOST;dbname=$DB_NAME";
$db = new PDO($dsn, $DB_USER, $DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM `snippets` ORDER BY _ID ASC";
$prep = $db->prepare($query);
$prep->execute();
$count = $prep->rowCount();
$half = round($count/2);
$dsn2 = "mysql:host=$DB_HOST;dbname=$DB_NAME";
$db2 = new PDO($dsn, $DB_USER, $DB_PASS);
$db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query2 = "SELECT * FROM `snippets` ORDER BY _ID ASC Limit " . $half;
$prep2 = $db2->prepare($query2);
$prep2->execute();
echo ' <div class="row">' . "\n";
echo ' <div class="large-12 columns">' . "\n";
echo ' <div class="panel">' . "\n";
while ($row = $prep2->fetch()) {
echo ' <div class="row">' . "\n";
echo ' <div class="large-12 columns">' . "\n";
echo ' <b>' . $row['CODE_NAME'] . '</b><br/><br/>' . "\n";
$timestamp = strtotime($row['CODE_TIMESTAMP']);
echo ' Date: ' . date("M d, Y h:m:s A", $timestamp).'<br/><br/>' . "\n";
echo ' </div>' . "\n";
echo ' </div>' . '<br/>' . "\n";
}
$db = null;
}
catch (PDOException $e) {
echo '<div class="row">';
echo '<div class="panel">';
echo 'Connection failed: ' . $e->getMessage();
echo '</div>';
echo '</div>';
}
echo ' </div>' . "\n";
echo ' </div>' . "\n";
echo ' </div>' . "\n";
?>
</div>
<div class="row">
<div class="small-6 small columns">
<?php
$DB_NAME = '';
$DB_HOST = '';
$DB_USER = '';
$DB_PASS = '';
try {
$dsn = "mysql:host=$DB_HOST;dbname=$DB_NAME";
$db = new PDO($dsn, $DB_USER, $DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM `snippets` ORDER BY _ID ASC";
$prep = $db->prepare($query);
$prep->execute();
$count = $prep->rowCount();
$half = round($count/2);
$dsn2 = "mysql:host=$DB_HOST;dbname=$DB_NAME";
$db2 = new PDO($dsn, $DB_USER, $DB_PASS);
$db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query2 = "SELECT * FROM `snippets` ORDER BY _ID ASC Limit " . $half . ',' . $half;
$prep2 = $db2->prepare($query2);
$prep2->execute();
/*
$dsn = "mysql:host=$DB_HOST;dbname=$DB_NAME";
$db = new PDO($dsn, $DB_USER, $DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM `snippets` ORDER BY _ID ASC LIMIT 20,19";
$prep = $db->prepare($query);
$prep->execute();
*/
echo ' <div class="row">' . "\n";
echo ' <div class="large-12 columns">' . "\n";
echo ' <div class="panel">' . "\n";
while ($row = $prep2->fetch()) {
echo ' <div class="row">' . "\n";
echo ' <div class="large-12 columns">' . "\n";
echo ' <b>' . $row['CODE_NAME'] . '</b><br/><br/>' . "\n";
$timestamp = strtotime($row['CODE_TIMESTAMP']);
echo ' Date: ' . date("M d, Y h:m:s A", $timestamp).'<br/><br/>' . "\n";
echo ' </div>' . "\n";
echo ' </div>' . '<br/>' . "\n";
}
$db = null;
}
catch (PDOException $e) {
echo '<div class="row">';
echo '<div class="panel">';
echo 'Connection failed: ' . $e->getMessage();
echo '</div>';
echo '</div>';
}
echo ' </div>' . "\n";
echo ' </div>' . "\n";
echo ' </div>' . "\n";
?>
</div>
</div>
</div>
<?php include 'includes/footer.php';?>
</body>
Related
I have a database with three tables "Cantiere "Affidataria "SubAffidataria"
"Cantiere" has a 1 to N relationship with Affidataria "Affidataria" has a 1 to N relationship with subAffidataria
so in Affidataria there is a fk of "Cantiere" called "fkIdCantiere" and in subAffidataria there is a fk of "Affidataria" called "fkIDAffidataria"
my problem is to go from a "function" to the id of fkIdAffidataria
in fact, if you notice in the screenshot you see the carers but not the sub-delegates. so I have to make sure to save the fkIdAffidataria to put it in the QUERY ..
enter image description here
"0 results" indicates that the query did not find any subAffidataria .. when in fact they are in the database
<!DOCTYPE html>
<?php
session_start();
if(!isset($_SESSION["username"]))
{
header('location: ../index.php');
}
else
{
?>
<?php
$servername = "localhost";
$username = "progettocantiere";
$password = "";
$dbname = "my_progettocantiere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$idCantiere = $_GET['idCantiere'];
$sql1 = "SELECT idAffidataria,nomeCantiere,fkIDCantiere
FROM Affidataria
WHERE fkIDCantiere = '$idCantiere'";
echo($idAffidataria);
$idAffidataria = $_GET['idAffidataria'];
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
// output data of each row
while($row = $result1->fetch_assoc()) {
echo'<br><br><br>';
echo '<h3>Affidataria</h3>';
echo '<a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '">' . $row["nomeCantiere"] . '</a>';
echo '<a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '">Stampa PDF ' . $row["nomeCantiere"] . '</a>';
echo '<a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '">Esporta Directory Interna ' . $row["nomeCantiere"] . '</a>';
echo '<a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '">Stampa Personale ' . $row["nomeCantiere"] . '</a>';
echo '<a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '">Esporta Directory Personale ' . $row["nomeCantiere"] . '</a>';
echo '<a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '">Stampa Mezzi ' . $row["nomeCantiere"] . '</a>';
echo '<a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '">Esporta Directory Mezzi ' . $row["nomeCantiere"] . '</a>';
}
echo'<br><br><br>';
} else {
echo "0 results";
}
$conn->close();
?>
//subAffidatario
<?php
$servername = "localhost";
$username = "progettocantiere";
$password = "";
$dbname = "my_progettocantiere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "SELECT * FROM SubAffidatario
WHERE fkIdAffidataria = '$idAffidataria'";
echo($idSubAffidatario);
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
// output data of each row
while($row = $result1->fetch_assoc()) {
echo'<br><br><br>';
echo '<a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/subAffidatario.php?idSubAffidatario=' . $row["idSubAffidatario"] . '">' . $row["ragioneSocialeSubAffidatario"] . '</a>';
}
echo'<br><br><br>';
echo 'Nuovo Cantiere +';
} else {
echo "0 results";
}
$conn->close();
?>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Progetto Cantiere</title>
<!-- Bootstrap -->
<link href="../paginaIniziale/css/bootstrap-4.0.0.css" rel="stylesheet">
</head>
<body>
</body>
</html>
<?php } ?>
I currently have my page like this, www.page.com/bars.php?monday, www.page.com/bars.php?tuesday, etc. Depending on what day is set, I display different content. Here is how I do it:
if (isset($_GET['monday']) && empty($_GET['monday'])) {
$query = "SELECT * FROM `bars_mon`";
$result = mysql_query($query) or die("no query");
$objects = array();
while($row = mysql_fetch_assoc($result)) {
$objects[] = $row;
}
foreach($objects as $object) {
echo
'<div class="bars-loc-cont">
<img src="' . $object['img_link'] . '" />
<div class="bars-info">
<p class="bars-title">' . $object['title'] . '</p>
<p class="bars-line-1">' . $object['line_1'] . '</p>
<p class="bars-line-2">' . $object['line_2'] . '</p>
<p class="bars-line-3">' . $object['line_3'] . '</p>
<p class="bars-line-4">' . $object['line_4'] . '</p>
<p class="bars-line-5">' . $object['line_5'] . '</p>
</div>
</div>';
}
} else if (isset($_GET['tuesday']) && empty($_GET['tuesday'])) {
$query = "SELECT * FROM `bars_tues`";
$result = mysql_query($query) or die("no query");
$objects = array();
while($row = mysql_fetch_assoc($result)) {
$objects[] = $row;
}
foreach($objects as $object) {
echo
'<div class="bars-loc-cont">
<img src="' . $object['img_link'] . '" />
<div class="bars-info">
<p class="bars-title">' . $object['title'] . '</p>
<p class="bars-line-1">' . $object['line_1'] . '</p>
<p class="bars-line-2">' . $object['line_2'] . '</p>
<p class="bars-line-3">' . $object['line_3'] . '</p>
<p class="bars-line-4">' . $object['line_4'] . '</p>
<p class="bars-line-5">' . $object['line_5'] . '</p>
</div>
</div>';
}
} else if (isset($_GET['wednesday']) && empty($_GET['wednesday'])) {
$query = "SELECT * FROM `bars_wed`";
$result = mysql_query($query) or die("no query");
$objects = array();
while($row = mysql_fetch_assoc($result)) {
$objects[] = $row;
}
foreach($objects as $object) {
echo
'<div class="bars-loc-cont">
<img src="' . $object['img_link'] . '" />
<div class="bars-info">
<p class="bars-title">' . $object['title'] . '</p>
<p class="bars-line-1">' . $object['line_1'] . '</p>
<p class="bars-line-2">' . $object['line_2'] . '</p>
<p class="bars-line-3">' . $object['line_3'] . '</p>
<p class="bars-line-4">' . $object['line_4'] . '</p>
<p class="bars-line-5">' . $object['line_5'] . '</p>
</div>
</div>';
}
} else if (isset($_GET['thursday']) && empty($_GET['thursday'])) {
$query = "SELECT * FROM `bars_thurs`";
$result = mysql_query($query) or die("no query");
$objects = array();
while($row = mysql_fetch_assoc($result)) {
$objects[] = $row;
}
foreach($objects as $object) {
echo
'<div class="bars-loc-cont">
<img src="' . $object['img_link'] . '" />
<div class="bars-info">
<p class="bars-title">' . $object['title'] . '</p>
<p class="bars-line-1">' . $object['line_1'] . '</p>
<p class="bars-line-2">' . $object['line_2'] . '</p>
<p class="bars-line-3">' . $object['line_3'] . '</p>
<p class="bars-line-4">' . $object['line_4'] . '</p>
<p class="bars-line-5">' . $object['line_5'] . '</p>
</div>
</div>';
}
} else if (isset($_GET['friday']) && empty($_GET['friday'])) {
$query = "SELECT * FROM `bars_fri`";
$result = mysql_query($query) or die("no query");
$objects = array();
while($row = mysql_fetch_assoc($result)) {
$objects[] = $row;
}
foreach($objects as $object) {
echo
'<div class="bars-loc-cont">
<img src="' . $object['img_link'] . '" />
<div class="bars-info">
<p class="bars-title">' . $object['title'] . '</p>
<p class="bars-line-1">' . $object['line_1'] . '</p>
<p class="bars-line-2">' . $object['line_2'] . '</p>
<p class="bars-line-3">' . $object['line_3'] . '</p>
<p class="bars-line-4">' . $object['line_4'] . '</p>
<p class="bars-line-5">' . $object['line_5'] . '</p>
</div>
</div>';
}
} else if (isset($_GET['saturday']) && empty($_GET['saturday'])) {
$query = "SELECT * FROM `bars_sat`";
$result = mysql_query($query) or die("no query");
$objects = array();
while($row = mysql_fetch_assoc($result)) {
$objects[] = $row;
}
foreach($objects as $object) {
echo
'<div class="bars-loc-cont">
<img src="' . $object['img_link'] . '" />
<div class="bars-info">
<p class="bars-title">' . $object['title'] . '</p>
<p class="bars-line-1">' . $object['line_1'] . '</p>
<p class="bars-line-2">' . $object['line_2'] . '</p>
<p class="bars-line-3">' . $object['line_3'] . '</p>
<p class="bars-line-4">' . $object['line_4'] . '</p>
<p class="bars-line-5">' . $object['line_5'] . '</p>
</div>
</div>';
}
} else if (isset($_GET['sunday']) && empty($_GET['sunday'])) {
$query = "SELECT * FROM `bars_sun`";
$result = mysql_query($query) or die("no query");
$objects = array();
while($row = mysql_fetch_assoc($result)) {
$objects[] = $row;
}
foreach($objects as $object) {
echo
'<div class="bars-loc-cont">
<img src="' . $object['img_link'] . '" />
<div class="bars-info">
<p class="bars-title">' . $object['title'] . '</p>
<p class="bars-line-1">' . $object['line_1'] . '</p>
<p class="bars-line-2">' . $object['line_2'] . '</p>
<p class="bars-line-3">' . $object['line_3'] . '</p>
<p class="bars-line-4">' . $object['line_4'] . '</p>
<p class="bars-line-5">' . $object['line_5'] . '</p>
</div>
</div>';
}
}
What I want to know is, when the user goes to www.page.com/bars.php only, how can I make so that I show something like if it were one of the days? And if i select a day, I would like to hide the bars.php content and display only the bars.php?'day' contents. Also, is there any way to make this code shorter? seems like there would be a much shorter way of doing this.
Url should be www.page.com/bars.php?day=tuesday
<?php
$day = (isset($_GET['day']) && !empty($_GET['day']))?$_GET['day']:'';
switch ($day) {
case "monday":
$query = "SELECT * FROM `bars_mon`";
break;
case "tuesday":
$query = "SELECT * FROM `bars_tues`";
break;
case "wednesday":
$query = "SELECT * FROM `bars_wed`";
break;
case "thursday":
$query = "SELECT * FROM `bars_thurs`";
break;
case "friday":
$query = "SELECT * FROM `bars_fri`";
break;
case "saturday":
$query = "SELECT * FROM `bars_sat`";
break;
case "sunday":
$query = "SELECT * FROM `bars_sun`";
break;
default:
$query = false;
}
if($query) {
$result = mysql_query($query) or die("no query");
$objects = array();
while($row = mysql_fetch_assoc($result)) {
$objects[] = $row;
}
foreach($objects as $object) {
echo
'<div class="bars-loc-cont">
<img src="' . $object['img_link'] . '" />
<div class="bars-info">
<p class="bars-title">' . $object['title'] . '</p>
<p class="bars-line-1">' . $object['line_1'] . '</p>
<p class="bars-line-2">' . $object['line_2'] . '</p>
<p class="bars-line-3">' . $object['line_3'] . '</p>
<p class="bars-line-4">' . $object['line_4'] . '</p>
<p class="bars-line-5">' . $object['line_5'] . '</p>
</div>
</div>';
}
} else {
echo 'your other code here';
}
?>
You need to get keys from $_GET using array_keys.
You will get day as first value.
Steps:
1) Check if $_GET is not empty.
2) Get keys of the array with array_keys.
3) Create an array of allowed week days.
4) Create another multidimensional array of days and database tables.
5) Where key is day and value is database table name.
6) If everything is fine, get name of database table using the day key.
7) This will be database table name.
8) If it is not empty, do the rest of work.
Code:
<?php
$days = isset($_GET) && ! empty($_GET) ? array_keys($_GET) : array();
$day = (current($days)) ? strtolower(current($days)) : '';
$allowedDays = array('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'); // Only allowed days.
if (! in_array($day, $allowedDays)) {
die('incorrect day');
}
$dbTables = array();
$dbTables['monday'] = 'bars_mon';
$dbTables['tuesday'] = 'bars_tues';
$dbTables['wednesday'] = 'bars_wed';
$dbTables['thursday'] = 'bars_thurs';
$dbTables['friday'] = 'bars_fri';
$dbTables['saturday'] = 'bars_sat';
$dbTables['sunday'] = 'bars_sun';
$tableName = isset($dbTables[$day]) ? $dbTables[$day] : '';
if (! empty($tableName)) {
$query = "SELECT * FROM `" . $tableName . "`";
// REST OF THE CODE...
}
?>
Here's a much simpler approach, that allows for a default:
calling with ?day=mon, for example
$days = array(
"mon", "tue", "wed", "thu", "fri", "sat", "sun",
);
$day = "mon";
if (isset($_GET['day']) && in_array($_GET['day'], $days)) {
$day = $_GET['day'];
}
$query = "SELECT * FROM `bars_$day`";
$result = mysqli_query($query) or die("no query");
$objects = array();
while($row = mysqli_fetch_assoc($result)) {
$objects[] = $row;
}
foreach($objects as $object) {
echo
'<div class="bars-loc-cont">
<img src="' . $object['img_link'] . '" />
<div class="bars-info">
<p class="bars-title">' . $object['title'] . '</p>
<p class="bars-line-1">' . $object['line_1'] . '</p>
<p class="bars-line-2">' . $object['line_2'] . '</p>
<p class="bars-line-3">' . $object['line_3'] . '</p>
<p class="bars-line-4">' . $object['line_4'] . '</p>
<p class="bars-line-5">' . $object['line_5'] . '</p>
</div>
</div>';
}
A few tips for future:
Seriously, stop using mysql_* functions - they're deprecated and unsafe. mysqli_* is better, but look into PDO and prepared statements.
Look into better error handling than calling die() - you want nice error messages for users and not raw text
Look into separating data logic (models) from presentation (views)
When each branch in an if/else chain uses the same 15 lines of code and only varies by one value, look at rewriting your code. Now, if you add new information to your output, you only have to update your code once and not seven times.
I think you have to pass monday or any other day like:
www.page.com/bars.php?day=monday
then
you can access like: $_GET['day']
At the beginning of the page, check if your $GET is empty
if (empty($_GET)) {
// no data passed by get, Set your get to your current day or any other day
$current_day = date('l');
$_GET[$current_day] = /**set it to what you want*/;
}
You should go with this:
<?php
# Check if weekday is passed in GET paramater in index `on`
# if not set then get current weekday using PHP date function
# to show current day records instead showing empty page
$day = (isset($_GET['on']) && !empty($_GET['on'])) ? $_GET['on'] : strtolower(date('l'));
$weekdays_and_db_tables = array(
'sunday' => 'sun',
'monday' => 'mon',
'tuesday' => 'tues',
'wednesday' => 'wed',
'thursday' => 'thurs',
'friday' => 'fri',
'saturday' => 'sat',
);
# Now check if weekdays is correct
if (!isset($weekdays_and_db_tables[$day]) or $weekdays_and_db_tables[$day] == '') {
die('Invalid weekday!');
}
# SQL Injection can cause here, so beware
# you should migrate all table in one and filter records using an extra column `weekday`
$query = printf("SELECT * FROM `bars_%s`", $weekdays_and_db_tables[$day]);
# instead separate table for each weekdays migrate in one and do:
$query_x = printf("SELECT * FROM `bars_weekdays` WHERE `weekday` = '%s'", $weekdays_and_db_tables[$day]);
$result = mysqli_query($query) or die("no query");
while($object = mysqli_fetch_assoc($result)) {
echo <<<HTML
<div class="bars-loc-cont">
<img src="{$object['img_link']}" />
<div class="bars-info">
<p class="bars-title">{$object['title']}</p>
<p class="bars-line-1">{$object['line_1']}</p>
<p class="bars-line-2">{$object['line_2']}</p>
<p class="bars-line-3">{$object['line_3']}</p>
<p class="bars-line-4">{$object['line_4']}</p>
<p class="bars-line-5">{$object['line_5']}</p>
</div>
</div>
HTML;
}
I seem to be getting Undefined offset 1 error when I hit submit. I have been trying to play with the numbers but nothing seems to help. I added a fourth column right after the commented last name. Before the addition the code worked. I realized later on that I needed that third column. Ever since then I get an error and can not update the sql table.
Thank you in advance,
Avi
<!DOCTYPE html>
<?php
echo '<link rel="stylesheet" type="text/css" href="css/newStyle.css"></head>';
session_start();
if (isset($_SESSION['loggedIn']) && ($_SESSION['loggedIn'] == true) && $_SESSION['admin'] == true) {
echo "<br><h3>Welcome to the administrative area Prof. " . $_SESSION['firstname'] . "!</h3><br><br>";
} else {
//echo "<br>Please log in first to see this page.";
header ('Location: index.php');
}
require_once 'login.php';
$connection = new mysqli($hn,$un,$pw,$db);
if($connection->connect_error) die($connection->connect_error);
if(isset($_POST['submit'])){
for($i = 0; $i < $_POST['totalGrades']; $i++){
echo $i . ': ' . $_POST['grade' .$i] . '<br>';
$parts = explode("|", $_POST['grade' .$i]);
$newGrade = "UPDATE Grades SET grade = '" . $parts[1] . "' WHERE gradeID = " .$parts[0];
$result = $connection->query($newGrade);
}
}
$username = "";
$courseId = "";
$grade = "";
$courseName = "";
?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
<form method= "post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<link rel="stylesheet" href="css/style.css">
<?php
// $courseSct =
"SELECT username, courseName, grade, gradeID FROM Courses\n"
// . "JOIN Grades\n"
// . "ON courses.courseId = Grades.courseId";
$courseSct =
"SELECT u.firstname, u.lastname, c.courseName, g.grade "
. " FROM Grades g "
. " INNER JOIN Courses c ON c.courseID = g.courseID "
. " INNER JOIN Users u ON u.userID = g.userID "
. " WHERE c.professorID = " .$_SESSION['userID'];
$result = $connection->query($courseSct);
$rows = $result->num_rows;
echo
"<table border = '1' width = '50%'>"
. "<caption><h2>Grades Table</h2></caption>"
. "<tr>"
. '<th>First Name</th>'
. "<th>Last Name</th>"
. "<th>Course Name</th>"
. "<th>Grade</th>"
//. "<th>New Value</th>"
. "</tr>";
for($j = 0; $j < $rows; ++$j) {
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo
"<tr>" .
"<td>" . $row[0] . "</td>" . //First Name
"<td>" . $row[1] . "</td>" . //Last Name
"<td>" . $row[2] . "</td>";
"<td>"; //Grade
echo '<select name="grade' . $j . '" size="1" id="' . $row[3] . '">';
echo '<option value="select">Select</option>';
$letterGrade = 'A';
for($x = 0; $x < 6; $x++) {
echo '<option value="' . $row[3] . '|' . $letterGrade . '"';
if($letterGrade == $row[3]) {
echo ' selected';
}
echo '>' . $letterGrade++ . '</option>';
}
echo '</select><br>'. "</td>" . "</tr>";
}
echo "</table>";
?>
<input type="hidden" name="totalGrades" value="<?php echo $rows;?>">
<br>
<input type="submit" name="submit" value="Submit">
<br>
</form>
<a href='index.php?logout'><br>click here to log out<br></a>
</body>
</html>
Have you tried a foreach instead?
if(isset($_POST['submit'])){
foreach($_POST['totalGrades'] as $key => $value) {
echo $key . ': ' . $value . '<br>';
$parts = explode("|", $value);
$newGrade = "UPDATE Grades SET grade = '" . $parts[1]
. "' WHERE gradeID = " .$parts[0];
$result = $connection->query($newGrade);
}
}
I have a system where users can send and receive messages and I need to make a way for them to directly reply to the messages.
This is a test code to make the page echo what should be retrieved and set as a session, but it is not echoing anything.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Clan Kaos ● View Post</title>
<link rel="stylesheet" type="text/css" href="include/style/content.css" />
</head>
<body>
<?php
include ("include/header.html");
include ("include/sidebar.html");
include ("include/testpost.html");
?>
<div class="container">
<?php session_start();
require_once('appvars.php');
require_once('connectvars.php');
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query = "SELECT username FROM kaoscraft_user WHERE user_id = '" . $_SESSION['user_id'] . "'";
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($data);
$username1 = $row['username'];
// Grab the profile data from the database
$query = "SELECT `to`, `from`, rank, gender, picture, title, msg FROM kaoscraft_pm WHERE `to` = '$username1' ORDER BY msg_id DESC";
$data = mysqli_query($dbc, $query);
$gender = $row['gender'];
$username2 = $_SESSION['reply'];
while ($row = mysqli_fetch_array($data)) {
$_SESSION['reply'] = $row['from'];
echo '<div class="viewpost">';
echo '<div class="vpside">';
if(!empty($row['picture'])) {
echo '<img class="pictest" src="' . MM_UPLOADPATH . $row['picture'] . '" alt="' . MM_UPLOADPATH . 'nopic.png' . '" />';
}
if(!empty($row['from'])) {
echo '<p>From:<br />' . $row['from'] . '</p>';
echo '<p> ' . $username2 . '</p>';
}
if(!empty($row['rank'])) {
echo '<p>Rank:<br />' . $row['rank'] . '</p>';
}
if(!empty($row['gender'])){
echo '<p>Gender:<br /> ' . $row['gender'] . '</p>';
}
echo '</div>';
if(!empty($row['title'])) {
echo'<h4><u>' .$row['title']. '</u></h4>';
}
if(!empty($row['msg'])) {
echo '<p class="">' . $row['msg'] . '</p>';
}
echo '<div class="sig">';
if(!empty($row['bio'])) {
echo '<p>' . $row['bio'] . '</p>';
}
echo '</div>';
echo '</div><br />';
}
mysqli_close($dbc);
?>
I need the session $_SESSION['reply'] to be set as the variable $username2 and it does not seem to be working.
Move session_start(); on top of the PHP code. You are accessing $_SESSION['reply'] = $username2; before that which wont work.
What I was doing was incorrect. I had to move
$_SESSION['reply'] = $row['from'];
$username2 = $_SESSION['reply'];`
from after the query to
while ($row = mysqli_fetch_array($data)) {
$_SESSION['reply'] = $row['from'];
$username2 = $_SESSION['reply'];`
and then it echo'd correctly. Thanks for the help from everyone :)
I have this code to pull data from the database and insert the data into one of 4 columns,
I have spent a whole day searching and just cant seem to find out how to do it..
Ideally, I want to select all from database and then where the fetch array has a column id of 1 - echo that then the sama for the next column etc..
<?php
echo '<div class="column grid_3 clearfix" id="column0" >';
echo ' ';
$user_sites_0=mysqli_query($connection, "SELECT * FROM user_sites WHERE column_id='0' ORDER BY sort_no");
if(!$user_sites_0) {
echo 'No sites added, please <a class="addsite" href="#">add one now</a>';
}
else {
while($user_site_0=mysqli_fetch_array($user_sites_0))
{
$id = stripslashes($user_site_0['id']);
$site_name = stripslashes($user_site_0['site_name']);
$site_address = stripslashes($user_site_0['site_address']);
$site_desc = stripslashes($user_site_0['site_desc']);
$site_category = stripslashes($user_site_0['site_category']);
$getImage = 'http://immediatenet.com/t/s?Size=1024x768&URL='.$site_address;
echo '<div class="dragbox" id="item'.$id.'">';
echo '<h2 class="h2handle">'.$site_name.' <span class="close"><img src="assets/img/closepanel.png"></span></h2>';
echo '<div class="dragbox-content" ';
if($user_site_0['collapsed']==1)
echo 'style="display:none;" ';
echo '>';
echo '<p><a class="sitelink" href="' . $site_address . '" title="'.$site_name.'"><img src="'.$getImage.'" alt="'.$site_name.'" title="'.$site_name.'"/></a>';
echo '<p>' . $site_category . '</p>';
echo '<p>' . $site_address . '</p>';
echo '<p>' . $site_desc . '</p>';
echo' </div>
</div>';
}
}
echo '</div>';
?>
<?php
echo '<div class="column grid_3 clearfix" id="column1" >';
echo ' ';
$user_sites_1=mysqli_query($connection, "SELECT * FROM user_sites WHERE column_id='1' ORDER BY sort_no");
if(!$user_sites_1) {
echo '';
}
else {
while($user_site_1=mysqli_fetch_array($user_sites_1))
{
$id = stripslashes($user_site_1['id']);
$site_name = stripslashes($user_site_1['site_name']);
$site_address = stripslashes($user_site_1['site_address']);
$site_desc = stripslashes($user_site_1['site_desc']);
$site_category = stripslashes($user_site_1['site_category']);
$getImage = 'http://immediatenet.com/t/s?Size=1024x768&URL='.$site_address;
echo '<div class="dragbox" id="item'.$id.'">';
echo '<h2 class="h2handle">'.$site_name.' <span class="close"><img src="assets/img/closepanel.png"></span></h2>';
echo '<div class="dragbox-content" ';
if($user_site_1['collapsed']==1)
echo 'style="display:none;" ';
echo '>';
echo '<p><a class="sitelink" href="' . $site_address . '" title="'.$site_name.'"><img src="'.$getImage.'" alt="'.$site_name.'" title="'.$site_name.'"/></a>';
echo '<p>' . $site_category . '</p>';
echo '<p>' . $site_address . '</p>';
echo '<p>' . $site_desc . '</p>';
echo' </div>
</div>';
}
}
echo '</div>';
?>
<?php
echo '<div class="column grid_3 clearfix" id="column2">';
echo ' ';
$user_sites_2=mysqli_query($connection, "SELECT * FROM user_sites WHERE column_id='2' ORDER BY sort_no");
if(!$user_sites_2) {
echo '';
}
else {
while($user_site_2=mysqli_fetch_array($user_sites_2))
{
$id = stripslashes($user_site_2['id']);
$site_name = stripslashes($user_site_2['site_name']);
$site_address = stripslashes($user_site_2['site_address']);
$site_desc = stripslashes($user_site_2['site_desc']);
$site_category = stripslashes($user_site_2['site_category']);
$getImage = 'http://immediatenet.com/t/s?Size=1024x768&URL='.$site_address;
echo '<div class="dragbox" id="item'.$id.'">';
echo '<h2 class="h2handle">'.$site_name.' <span class="close"><img src="assets/img/closepanel.png"></span></h2>';
echo '<div class="dragbox-content" ';
if($user_site_2['collapsed']==1)
echo 'style="display:none;" ';
echo '>';
echo '<p><a class="sitelink" href="' . $site_address . '" title="'.$site_name.'"><img src="'.$getImage.'" alt="'.$site_name.'" title="'.$site_name.'"/></a>';
echo '<p>' . $site_category . '</p>';
echo '<p>' . $site_address . '</p>';
echo '<p>' . $site_desc . '</p>';
echo' </div>
</div>';
}
}
echo '</div>';
?>
<?php
echo '<div class="column grid_3 clearfix" id="column3">';
echo ' ';
$user_sites_3=mysqli_query($connection, "SELECT * FROM user_sites WHERE column_id='3' ORDER BY sort_no");
while($user_site_3=mysqli_fetch_array($user_sites_3))
{
$id = stripslashes($user_site_3['id']);
$site_name = stripslashes($user_site_3['site_name']);
$site_address = stripslashes($user_site_3['site_address']);
$site_desc = stripslashes($user_site_3['site_desc']);
$site_category = stripslashes($user_site_3['site_category']);
$getImage = 'http://immediatenet.com/t/s?Size=1024x768&URL='.$site_address;
echo '<div class="dragbox" id="item'.$id.'">';
echo '<h2 class="h2handle">'.$site_name.' <span class="close"><img src="assets/img/closepanel.png"></span></h2>';
echo '<div class="dragbox-content" ';
if($user_site_3['collapsed']==1)
echo 'style="display:none;" ';
echo '>';
echo '<p><a class="sitelink" href="' . $site_address . '" title="'.$site_name.'"><img src="'.$getImage.'" alt="'.$site_name.'" title="'.$site_name.'"/></a>';
echo '<p>' . $site_category . '</p>';
echo '<p>' . $site_address . '</p>';
echo '<p>' . $site_desc . '</p>';
echo' </div>
</div>';
}
echo '</div>';
?>
The code looks a right state.. Could I do it better?
Use for and change the code, some code :
<?php
for ($i=0; $i<4; $i++)
{
echo '<div class="column grid_3 clearfix" id="column'.$i.'" >';
echo ' ';
$user_sites=mysqli_query($connection, "SELECT * FROM user_sites WHERE column_id='".$i."' ORDER BY sort_no");
if(!$user_sites) {
echo 'No sites added, please <a class="addsite" href="#">add one now</a>';
}
else
{
while($user_site=mysqli_fetch_array($user_sites))
{
... // Do it yourself
maybe
function get_site($column_id){
$str = "";
$user_sites = mysqli_query($connection, "SELECT * FROM user_sites WHERE column_id='".$column_id."' ORDER BY sort_no");
if(!$user_sites_0) {
echo 'No sites added, please <a class="addsite" href="#">add one now</a>';
}
else {
while($user_site_0=mysqli_fetch_array($user_sites_0))
{
$id = stripslashes($user_site_0['id']);
$site_name = stripslashes($user_site_0['site_name']);
$site_address = stripslashes($user_site_0['site_address']);
$site_desc = stripslashes($user_site_0['site_desc']);
$site_category = stripslashes($user_site_0['site_category']);
$getImage = 'http://immediatenet.com/t/s?Size=1024x768&URL='.$site_address;
$str.= '<div class="dragbox" id="item'.$id.'">';
$str.= '<h2 class="h2handle">'.$site_name.' <span class="close"><img src="assets/img/closepanel.png"></span></h2>';
$str.= '<div class="dragbox-content" ';
if($user_site_0['collapsed']==1)
echo 'style="display:none;" ';
$str.= '>';
$str.= '<p><a class="sitelink" href="' . $site_address . '" title="'.$site_name.'"><img src="'.$getImage.'" alt="'.$site_name.'" title="'.$site_name.'"/></a>';
$str.= '<p>' . $site_category . '</p>';
$str.= '<p>' . $site_address . '</p>';
$str.= '<p>' . $site_desc . '</p>';
$str.=' </div>
</div>';
}
}
$str.='</div>';
return $str;}
echo '<div class="column grid_3 clearfix" id="column0">';
echo ' ';
echo oget_site(0);
echo '<div class="column grid_3 clearfix" id="column1">';
echo ' ';
echo oget_site(1);
//....