Sorting with MySQL and PHP - php

So right now I have my MySql database on phpmyadmin connected to my PHP script. It lists 50 different NFL players and their stats from last year. I would like to be able to list a dropdown box to where I can sort the players by any of the categories (i.e. Receptions, Rec Yds, TDs, etc.) but am not sure how I would do this..?? I have a switch statement in there but it doesn't seem to be doing anything right now.
<!DOCTYPE html>
<html>
<!-- Seth Rataiczak -->
<head>
<title>PHP Project</title>
<style>
table,th,td {
border:1px solid navy;
}
body {
background-color:peachpuff;
}
</style>
</head>
<body>
<?php
// database connection
$db_hostname='localhost';
$db_username='root';
$db_password='';
$db_database='Project';
$connection = new mysqli( $db_hostname,
$db_username,
$db_password,
$db_database);
//MySQL Select Statement
$sort = "";
if(isset($_GET['sort'])) {
switch ($_GET['sort'] ) {
case 0:
$sort = ' ORDER BY Team DESC';
break;
case 1:
$sort = ' ORDER BY Pos DESC';
break;
case 2:
$sort = ' ORDER BY Rec DESC';
break;
case 3:
$sort = ' ORDER BY Yds DESC';
break;
case 4:
$sort = ' ORDER BY Avg DESC';
break;
case 5:
$sort = ' ORDER BY Yds/G DESC';
break;
case 6:
$sort = ' ORDER BY TD DESC';
break;
}
}
$sql = "SELECT * FROM NFL_2014_Receiving WHERE Field=1" . $sort;
$result = $connection->query($sql);
if (!$result) die ($connection->error);
$n = $result->num_rows;
$nfl = array();
// echos the table headers
echo "<table>
<tr><th>ID</th><th>Player</th><th>Team</th>
<th>Position</th><th>Receptions</th>
<th>Receiving Yards</th><th>Avg Yds/Catch</th>
<th>Avg Yds/Game</th><th>Touchdowns</th></tr>";
// echos the table data
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
$nfl[$row['iD']] = $row['Player'];
if(!isset($_POST['hide']) || $_POST['hide'] != $row['iD']){
echo "<tr><td width=20>" . $row['iD'] . "</td><td width=150>" . $row['Player'] . "</td><td width=40>" .
$row['Team'] . "</td><td width=30>" . $row['Pos'] . "</td><td width=30>" .
$row['Rec'] . "</td><td width=40>" . $row['Yds'] . "</td><td width=30>" .
$row['Avg'] . "</td><td width=40>" . $row['Yds/G'] . "</td><td width=20>" .
$row['TD'] . "</td></tr>";
}
}
echo "</table><br>";
//dropdown box
echo "<form method='post' action='index.php'><select name='hide'>";
foreach($nfl as $key=>$value){
echo "<option value='".$key."'>".$value."</option>";
}
// submit button
echo "<input type='submit' value='Submit'>";
echo "</select></form>";
?>
</body>
</html>

You are setting a POST method action and you are searching GET for value.
To be clear:
You can change your form method to get <form method='get' action='index.php'> or change your php value $_GET['sort'] to $_POST['sort']
I m quite sure this is your problem but you can echo your $sql variable to see what your query does ;)

the input submit is inside of select tag. must be after select, not inside.
the method of form must be equal to the parameter received, in this case must be GET.
the name of the select must be 'sort' instead of 'hide'

Related

Create a combobox with a php associative array and insert a value into the db

<?
include_once("common_func.php");
$dataArr=array();
$dataArr["1"] = "one";
$dataArr["2"] = "two";
$dataArr["3"] = "three";
function createCombobox2($getArr,$boxName){
$dump2 = "";
$dump2 = "<select sTime = \"" . $boxName . "\">";
foreach($getArr as $comKey=>$comVal){
$dump2 .="<option value=\"" . $comKey . "\">" . $comVal . "</option>";
}
$dump2 .= "</select>";
return $dump2;
}
switch($mode){
case "add":
break;
}
?>
<div style="border:3 solid gray;padding:20px">
<form action="action.php?mode=<?=$mode?>" method="post">
<table align = "center" border="1" width="60%">
<? if($mode=="add") { ?>
<tr>
<th>접수분야</th><input name = "sField" value="<?=$noField?>" > </td>// error is here(I don't know how to define this place.)
</tr>
<? } else { ?>
//Skip the unnecessary part
<? } ?>
I would like to put the value of combobox in db. All other values have been inserted in db, but no progress has been made because the values in the combo box have not been inserted. If my question is wrong, I want feedback.
common_func.php
function excuteQuery($mode,$fieldArr,$tableName,$whereStr,$connName){
switch($mode){
case "add": //Insert data
$tmpLeft=""; $tmpRight="";
foreach($fieldArr as $keyName => $dataVal){
if(strlen($dataVal)>0){
$tmpLeft .= $keyName . ","; $tmpRight .= "\"$dataVal\",";
}
}
$strSql="INSERT INTO $tableName (" .substr($tmpLeft,0,-1) . ") VALUES(" . substr($tmpRight,0,-1) . ")";
break;

Passing value from SQL query to another SQL query in php

I want to use a variable that comes from a table i MySQL and pass it to Another SQL-Query with PHP. Can´t get it to work and I can´t find out why.
Here is the code:
<html>
<head><title></title></head>
<body>
<div>
<?php
if (isset($_GET['read_blog_posts_scrolling']))
{
$result = mysql_query("SELECT blogpost.Blogpost_title, blog.Blogwriters_name, blogpost.Date
FROM blog
INNER JOIN blogpost ON blog.BlogID=blogpost.BlogID
WHERE blog.BlogID='$blogs_profile_id' // Here it is, it says undefined variable
ORDER BY blogpost.Date DESC")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<p>';
echo "Titel: " . "<strong>" . $row['Blogpost_title'] . "</strong>" . " - Bloggare " . $row['Blogwriters_name'] . " " . $row['Date'] . '<br />';
echo '<hr />';
echo '</p>';
}
}
?>
<?php
$result = mysql_query("SELECT BlogID, Blogwriters_name FROM blog")
or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$blogs_profile_id = $row['BlogID']; // I want to pass this value to above and use it in the query
echo '<p>';
echo $row['Blogwriters_name'] . '<br />';
//When clicking in this link I want the query to execute and values in BlogID to be passed
echo 'Choose blogwriter';
echo '</p>';
?>
</div>
</body>
</html>
it says the variable is undefined. How can I define it and pass the value when the a href-link is clicked?
Error is clear. Undefined variable:
You didn't defined this variable anywhere
before select statement
$blogs_profile_id
I think you need to add this variable in query string and get from $_GET.
UPDATE 1:
You have following issues in your code.
Missing blog_profile_id in your query string.
Undefined variable means you are using a variable but didn't defined.
Using mysql_* extension its deprecated
Solution:
Replace this:
echo 'Choose blogwriter';
With:
echo 'Choose blogwriter';
And than use that:
if (intval($_GET['blog_id']) > 0)
{
$blogs_profile_id = intval( $_GET['blog_id']);
$result = mysql_query("SELECT blogpost.Blogpost_title, blog.Blogwriters_name, blogpost.Date FROM blog INNER JOIN blogpost ON blog.BlogID=blogpost.BlogID WHERE blog.BlogID=".$blogs_profile_id." ORDER BY blogpost.Date DESC")
or die(mysql_error());
.....
Change the order of your queries. The second query code has to be coming first in order as below
<html>
<head><title></title></head>
<body>
<div>
<?php
$result = mysql_query("SELECT BlogID, Blogwriters_name FROM blog")
or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$blogs_profile_id = $row['BlogID']; // I want to pass this value to above and use it in the query
echo '<p>';
echo $row['Blogwriters_name'] . '<br />';
//When clicking in this link I want the query to execute and values in BlogID to be passed
echo 'Choose blogwriter';
echo '</p>';
?>
<?php
if (isset($_GET['read_blog_posts_scrolling']))
{
$result = mysql_query("SELECT blogpost.Blogpost_title, blog.Blogwriters_name, blogpost.Date
FROM blog
INNER JOIN blogpost ON blog.BlogID=blogpost.BlogID
WHERE blog.BlogID='"+$blogs_profile_id+"' // Here it is, it says undefined variable
ORDER BY blogpost.Date DESC")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<p>';
echo "Titel: " . "<strong>" . $row['Blogpost_title'] . "</strong>" . " - Bloggare " . $row['Blogwriters_name'] . " " . $row['Date'] . '<br />';
echo '<hr />';
echo '</p>';
}
}
?>
</div>
</body>
</html>

Whenever I reload/refresh my page, it doubles the mysql query? [PHP]

I'm working with our project and I noticed that whenever I refresh my page the mysql query repeats itself. When I click a submit button It will go to same page and it will perform the query. Even though i used isset() method to the submitting button, still the query repeats when I refresh/reload the page. Thank you :) !
<html>
<body>
<head>
<link rel="stylesheet" type="text/css" href="Homepagestyle.css">
</head>
<form method = "POST" action = "Forum.php">
<?php
session_start();
mysql_connect("127.0.0.1", "root", "toor");
mysql_select_db("matutorials");
echo "Welcome " . "<a href = 'UserProf.php'>". $_SESSION['username'] . "</a> <br>";
if (isset($_POST['btnProg'])){
echo $_SESSION['prog'] . "<br>";
} else if (isset($_POST['btnNet'])){
echo $_SESSION['net'] . "<br>";
}
?>
<center><font face = 'verdana'><textarea cols = 70 rows = 6 name = 'txtpost'></textarea></font></center><br>
<center><input type = 'submit' name = 'btnPost'></center><br> <br>
<center><table>
<?php
if (isset($_POST['btnProg'])){
$_SESSION['pasamoto'] = 1;
$capRows = "SELECT * FROM page_post WHERE category_id = 1 ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer)){
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
?>
</table> </center>
<?php
session_start();
if(isset($_POST['btnPost'])){
$post_content = $_POST['txtpost'];
$dttime = date("Y-m-d") . " " . date("h:i:sa");
$var = $_SESSION['pasamoto'];
if ($var == 1){
$addpost = "INSERT INTO page_post(post,timestamps,category_id) VALUES ('$post_content','$dttime','$var')";
mysql_query($addpost);
$capRows = "SELECT * FROM page_post WHERE category_id = '".$var."' ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer)){
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
//}
if ($var == 2){
$addpost = "INSERT INTO page_post(post,timestamps,category_id) VALUES ('$post_content','$dttime','$var')";
mysql_query($addpost);
$capRows = "SELECT * FROM page_post WHERE category_id = '".$var."' ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer)){
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
//}
?>
</form>
</body>
</html>
If you refresh a page after submitting you form, the POST will still be recognised by some browsers and will cause a second POST to the code. You should update your code to trigger the SQL query on a separate page or function, and then redirect the user to the success / thanks page, where refreshing won't duplicate the query.
Alternatively, you can have a hidden field on your page which contains a unique token and compare it with a cookie. On page load, you save the token to a cookie and to the hidden field on the form. When you submit the form, validate that the token in the hidden form field matches the cookie, then delete the cookie. Refreshing the page after submission will cause the token validation to fail, preventing a duplicate SQL insert.
Just wash out the form data by redirecting the page after insert query
like header('location:home.php')
As #PeeHaa suggested in the comments above use Post-Redirect-Get concept.
Modified your code a bit. Try below:
Forum.php
<head>
<link rel="stylesheet" type="text/css" href="Homepagestyle.css">
</head>
<body>
<form method="POST" action="Forum.php">
<?php
session_start();
mysql_connect("127.0.0.1", "root", "toor");
mysql_select_db("matutorials");
echo "Welcome " . "<a href = 'UserProf.php'>". $_SESSION['username'] . "</a> <br>";
if (isset($_GET['show']))
{
echo $_SESSION['prog'] . "<br>";
}
else if (isset($_GET['show']))
{
echo $_SESSION['net'] . "<br>";
}
?>
<center><font face = 'verdana'><textarea cols = 70 rows = 6 name = 'txtpost'></textarea></font></center><br>
<center><input type = 'submit' name = 'btnPost'></center><br> <br>
<center><table>
<?php
if (isset($_GET['show']))
{
$_SESSION['pasamoto'] = 1;
$capRows = "SELECT * FROM page_post WHERE category_id = 1 ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer))
{
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
?>
</table> </center>
<?php
if(isset($_POST['btnPost']))
{
$post_content = $_POST['txtpost'];
$dttime = date("Y-m-d") . " " . date("h:i:sa");
$var = $_SESSION['pasamoto'];
if ($var == 1)
{
$addpost = "INSERT INTO page_post(post,timestamps,category_id) VALUES ('$post_content','$dttime','$var')";
mysql_query($addpost);
$capRows = "SELECT * FROM page_post WHERE category_id = '".$var."' ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer))
{
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
if ($var == 2)
{
$addpost = "INSERT INTO page_post(post,timestamps,category_id) VALUES ('$post_content','$dttime','$var')";
mysql_query($addpost);
$capRows = "SELECT * FROM page_post WHERE category_id = '".$var."' ORDER BY timestamps DESC";
$iQuer = mysql_query($capRows);
while ($getRows = mysql_fetch_array($iQuer))
{
echo "<tr>";
echo "<td><div id = 'postsdiv'>" . $getRows['post'] . "</div><br>";
echo "</tr>";
}
}
}
header("Location:Forum.php?show=true"); // <==== Note this
?>
</form>
</body>
</html>
Explanation:
The above code will follow the Post-Redirect-Get pattern. The form will post the data to the same page and whatever task you want to perform after form post should be enclosed in,
if(isset($_POST['btnPost']))
{
...
}
and then redirect the user to the same page using,
header("Location:Forum.php?show=true");
the header function will redirect the user to the same page and the GET parameter show will decide what to show after the redirection. The content to show after redirection (or any other time) should be enclosed in,
if(isset($_GET['show']))
{
...
}

Retrieve Value from Multiple Looped Textarea

I've built a form for a short-answer quiz. Each question has multiple textboxes for answer (corresponding to instruction in the question i.e. list two components, three advantages, etc.). I've designed the form as such so that the answers can be evaluated independently against a set of answers. Each question can have many answer suggestions. Here is the 'answer' table structure:
CREATE TABLE IF NOT EXISTS `answer` (
`a_id` int(10) NOT NULL AUTO_INCREMENT,
`q_id` int(10) NOT NULL,
`a_text` text NOT NULL,
`a_keyword` text NOT NULL,
PRIMARY KEY (`a_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
This is the code of the form:
<?php
session_start();
if(isset($_SESSION['tf1_sid'])){
?>
<head>
<title>Dahlia | Formative Assessment</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" name="form1" method="post" action="s_ass_result_new.php">
<h2>Short-answer Questions</h2>
<table width="590" border="0" cellpadding="2" align="center">
<?php
// db connect
include("dbconn.php");
// db query for questions
$sql_q = "SELECT q_id, q_no, q_text, q_field FROM question";
$query_q = mysql_query($sql_q) or die("MySQL Error: " . mysql_error());
// start loop for questions
//$rad = 1;
while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){
$qfield = $data_q['q_field'];
$qno = $data_q['q_no'];
echo "<tr><td width='20' align='center' valign='top'><label><br /><input name='q_no' size='1' type='hidden' value=". $data_q['q_no'] .">". $data_q['q_no'] ."</label></td>";
echo "<td><br />". $data_q['q_text'] ." (<a href='s_help.php?s_id=". $_SESSION['tf1_sid'] ."&q_id=". $data_q['q_id'] ."' target='_blank'>Help</a>)</td>";
for($rad=1;$rad<=$qfield;$rad++){
echo "<tr><td></td><td><textarea name='answer_".$rad."' cols='55' rows='2' id='textarea1'></textarea></td></tr>";
echo "<script>document.getElementById('textarea1').focus()</script>";
//$rad++;
}
}
echo "<tr></tr><tr><td></td><td><input name='Submit' type='submit' value='Submit' onClick='return confirm(\"Are you sure?\")'></td></tr>";
mysql_free_result($query_q);
include("dbconn.php");
?>
</table>
</form>
</body>
</html>
<?php
}
else
{
header("Location:s_login.php");
}
?>
The form is displaying fine but I'm having trouble retrieving values being submitted through the text area. Below is the code to retrieve those values:
<?php
// include db connection file
include("dbconn.php");
session_start();
if(isset($_POST['Submit']))
{
$id = $_SESSION['tf1_sid'];
$qno = $_POST['q_no'];
$ansspc = $_POST['q_field'];
?>
<head>
<title>Dahlia | Formative Assessment</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Answer Review</h2>
<table width="590" border="0" cellpadding="2" align="center">
<?php
//db query to obtain i_id - to insert to RESULT table
$sql_i = "SELECT i_id FROM ins_stud WHERE s_id = '$id'";
$query_i = mysql_query($sql_i) or die("MySQL Error: " . mysql_error());
$data_i = mysql_fetch_assoc($query_i);
$ins_id = $data_i['i_id'];
//$j = 1;
$arr_ind = 1;
$atext = array(1);
$ans = array(1);
//FOR LOOP TO RETRIEVE VALUES FROM TEXT AREA
for($i=1;$i<=$q_no;$i++){
for($k=1;$k<=$ansspc;$k++){
$repStr = str_replace("1", $k, "answer_1");
echo "Question ". $i .": Answer: ". $repStr;
$ans[] = $_POST[$repStr];
echo $ans;
}
$sql_check = "SELECT a_text FROM answer WHERE q_id='$i'";
$query_ch = mysql_query($sql_check) or die("MySQL Error: " . mysql_error());
$data_ch = mysql_fetch_assoc($query_ch);
$atext[] = $data_ch['q_ans'];
//$j++;
}
...
It was working previously when I had the questions set with one text area each. What I intend to do is have each answer to be compared with each answer suggestion.
Example:
State two advantages of...
Two text area: ans1, ans2
Four suggested answers: soln1, soln2, soln3, soln4
So I'd compare ans1 with soln1, soln2, soln3, soln4 then the same goes for the ans2.
Edited:
//start loop for questions & answers
while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){
//process returned data
foreach ($_POST['answer'] as $questionNumber => $answerList){
echo "question " . $questionNumber . ": \n";
foreach ($answerList as $key => $answer){
$ans[] = $answer;
echo "answer " . $key . ": " . $answer . "\n";
}//end foreach_in
}//end foreach_out
$jawapan = explode(" ", $ans[$arr_ind]);
$jwpn = trim($jwpn);
foreach($jwpn as $eval){
if (stripos($atext[$arr_ind], $eval) !== false){ //$atext: query for answer suggestions
//answer match with first suggestion
echo "<p align='justify'><img src='image/mark.png' border='0' width='20' height='20'> ". $ans[$arr_ind]. "</p>";
}//if
{else
//answer doesn't match with first suggestion; check next suggestion
for($m=1;$m<=$box;$m++){...}// $box = no. of text area in form
}//else
echo "<p align='justify'><label><b>SUGGESTED ANSWER:</b> <br><input name='answer_".$rad."' type='hidden' value=''>". $atext[$arr_ind] . "</label></p>";
$arr_ind++;
}//foreach
Best is to use arrays in the naming of the textareas
Outputting the textarea (i left out all markup extras just to make it clear)
while ($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)) {
$qfield = $data_q['q_field'];
$qno = $data_q['q_no'];
for ($rad = 1; $rad <= $qfield; $rad++) {
echo "<textarea name='answer[" . $qno . "][" . $rad . "]' id='textarea_" . $qno . "_" . $rad . "'>";
}
}
and processing the returned data
foreach ($_POST['answer'] as $questionNumber => $answerList) {
echo "question " . $questionNumber . ": \n";
foreach ($answerList as $key => $answer) {
echo "answer " . $key . ": " . $answer . "\n";
}
}

use mysql data and put into a drop down

i have be been trying to put a count query into a drop down as i am creating a rating type system and based on the number of rows in a database i want to return a scale for example 1-5
<?php
// Ruth Gammack
session_start();
$page = 'index.php';
mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('group4') or die(mysql_error());
//echo "Done";
require_once "./includes/choices.inc.php";
if(isset($_GET["action"])){
switch($_GET["action"]) {
case "add":
addmodule();
break;
case "remove":
removemodule();
break;
case "empty":
emptychoice();
break;
}
reviewChoices();
// close database connection
dbClose($conn);
}
function modules(){
$get = mysql_query('SELECT * FROM module');
if (mysql_num_rows($get) == 0){
echo '<p>There are no Modules available at this time please check back later</p>';
}
else {
while ($get_row = mysql_fetch_assoc($get)) {
echo '<p>'.$get_row['moduleID'].'<br />'.$get_row['ModuleName'].'<br />'.$get_row['ModuleDesc'].'<br />'.$get_row['LecturerID'].'</p>';
// printing the list box select command
$query_disp=('SELECT moduleID, COUNT(*) FROM module');
$result_disp = mysql_query($query_disp);
echo "<select name=”selRating”>";
while($row = mysql_fetch_array($result_disp))
{
echo "<option value='" . $row['moduleID'] . "'>" . $row['moduleID'] . "</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
}
}
}
?>
i have tried many different ways but I have run out of ideas.
Maybe something like this (not tested)?
$query_disp=('SELECT moduleID, ModuleName, ModuleDesc, LecturerID, COUNT(*) AS cnt FROM module GROUP BY moduleID');
$select = "<select name=”selRating”>";
while($row = mysql_fetch_array($query_disp))
{
echo '<p>'.$get_row['moduleID'].'<br />'.$get_row['ModuleName'].'<br />'.$get_row['ModuleDesc'].'<br />'.$get_row['LecturerID'].'</p>';
$select += "<option value='" . $row['moduleID'] . "'>" . $row['ModuleName'] . " " . $row['cnt'] . "</option>";
}
$select += '</select>';
echo $select;

Categories