Edited, please scroll down
I am trying to display 3 variables which consist of data stored in a SQL database. However, only the first gets echoed successfully (topLeftUrl). It is worth noting that the same PHP file also receives data from an input (also in the same PHP file) and stores it in the same SQL database. This code was written for testing purposes and may not be entirely safe.
//Connect
$con = mysqli_connect ("localhost","noneedtoknow","noneedtoknow","noneedtoknow");
if (mysqli_connect_errno())
{
echo "Error: ", mysql_connect_error(), "<br>";
die ();
}
//Store input in SQL database
$result = mysqli_query ($con, "SELECT * FROM edit");
$message = stripslashes ($_POST ['message']);
if ($message !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$message' WHERE id='message'"); }
$topLeftNew = ($_POST ['topLeftUrl']);
if ($topLeftNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topLeftNew' WHERE id='topLeft'"); }
$topRightNew = ($_POST ['topRightUrl']);
if ($topRightNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topRightNew' WHERE id='topRight'"); }
//First echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topLeft" && $done2 == 0)
{
$topLeftUrl = $row["cont"];
}
}
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
//Second echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topRight" && $done3 == 0)
{
$topRightUrl = $row["cont"];
}
}
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
//Third echo
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "message" && $done == 0)
{
echo $row["cont"];
}
}
Edit:
I updated the code, and the problem seems to have changed. For some reason, echo $messageCont; displays an old value of cont WHERE id='message'. The database itself is updated successfully, though, and I see the new value of cont once I refresh the page/re-submit the form. Why do I not see the current value of cont immediately after form submission, though? Here is the new code:
/* Before <!DOCTYPE html> */
//Connect
$con = mysqli_connect ("localhost","noneedtoknow","noneedtoknow","noneedtoknow");
if (mysqli_connect_errno())
{
echo "Error: ", mysql_connect_error(), "<br>";
die ();
}
//Query and update
$result = mysqli_query ($con, "SELECT * FROM edit");
$message = stripslashes ($_POST ['message']);
if ($message !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$message' WHERE id='message'"); }
$topLeftNew = ($_POST ['topLeftUrl']);
if ($topLeftNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topLeftNew' WHERE id='topLeft'"); }
$topRightNew = ($_POST ['topRightUrl']);
if ($topRightNew !== '') {
mysqli_query ($con, "UPDATE edit SET cont='$topRightNew' WHERE id='topRight'"); }
//Query again and read
$done0 = 0;
$done1 = 0;
$done2 = 0;
mysqli_data_seek ($result, 0);
while ($row = mysqli_fetch_array ($result))
{
if ($row["id"] == "topLeft" && $done0 == 0)
{
$topLeftUrl = $row["cont"];
$done0 = 1;
}
else if ($row["id"] == "topRight" && $done1 == 0)
{
$topRightUrl = $row["cont"];
$done1 = 1;
}
else if ($row["id"] == "message" && $done2 == 0)
{
$messageCont = $row["cont"];
$done2 = 1;
}
else null;
}
/* After <!DOCTYPE html> */
/* Form code was omitted as it works perfectly. It is in this same file, though. */
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
echo $messageCont;
Any help is appreciated.
Edit: I only had to replace mysqli_data_seek () with the line beginning by $result (cut/paste). Thank you.
I ran into this same problem on my site....you run multiple mysql_fetch_array() on the same query ($result)...I thought this would work on my site but this failed for all but the first of 6 while loops which all referenced the same query on my site (I'm sorry but I don't remember the exact error message in my error_log). Try condensing your 3 while loops into 1 loop, something like this:
while ($row = mysqli_fetch_array ($result)) {
if ($row["id"] == "topLeft" && $done2 == 0) {
$topLeftUrl = $row["cont"];
} else if ($row["id"] == "topRight" && $done3 == 0) {
$topRightUrl = $row["cont"];
} else if ($row["id"] == "message" && $done == 0) {
echo $row["cont"];
} else null;
}
echo "<input type=\"text\" name=\"topRightUrl\" value=\"" . $topRightUrl . "\">";
echo "<input type=\"text\" name=\"topLeftUrl\" value=\"" . $topLeftUrl . "\">";
Related
I am having some issues for the last 5 hours. I've been trying to fix it and I can't seem to find a solution, so I hope you can help me!
So I have this vote.php script:
<?php
if(basename($_SERVER["PHP_SELF"]) == "vote.php") {
die("403 - Access Forbidden");
}
echo "<h2 class=\"text-left\">Vote</h2><hr/>";
$earnedpoints = false;
$insertnew = false;
$time = time();
$redirect = "";
$account = $mysqli->real_escape_string(preg_replace("/[^A-Za-z0-9 ]/", '', #$_POST['name']));
$siteid = $mysqli->real_escape_string(#$_POST['votingsite']);
$checkacc = $mysqli->query("SELECT * FROM accounts WHERE name = '$account'");
$countcheckacc = $checkacc->num_rows;
$row = $checkacc->fetch_assoc();
if($countcheckacc == 0 && isset($_POST['submit'])) {
$funct_error = "This account doesn't exist!";
}
if($row['loggedin'] > 0 && isset($_POST['submit'])) {
$funct_error = "This account is logged in!";
} elseif ($account == '' && isset($_POST['submit'])) {
$funct_error = 'You need to put in a username!';
} elseif(empty($_POST['votingsite']) && isset($_POST['submit'])){
$funct_error = "Please select a voting site";
} elseif(isset($_POST['submit'])) {
$checksite = $mysqli->query("SELECT * FROM ".$prefix."vote WHERE id = ".$siteid."");
$countchecksite = $checksite->num_rows;
if($countchecksite == 0 && isset($_POST['submit'])) {
$funct_error = "Invalid voting site.";
} else {
$result = $mysqli->query("SELECT *, SUM(times) as amount FROM ".$prefix."votingrecords WHERE NOT account='' AND NOT account='0' AND account='".$account."' AND siteid = '".$siteid."'") or die('Error - Could not look up vote record!');
$row = $result->fetch_assoc();
$sitequery = $mysqli->query("SELECT * FROM ".$prefix."vote WHERE id = '".$siteid."'");
$vsite = $sitequery->fetch_assoc();
$gvp = $vsite['gvp'];
$gnx = $vsite['gnx'];
$timecalc = $time - $row['date'];
if ($row['amount'] == '' || $timecalc > $vsite['waittime']) {
if($row['amount'] == '') {
$result = $mysqli->query("INSERT INTO ".$prefix."votingrecords (siteid, ip, account, date, times) VALUES ('".$siteid."', '".$ipaddress."', '".$account."', '".$time."', '1')") or die ('Error - Could not insert vote records!');
} else {
$result = $mysqli->query("UPDATE ".$prefix."votingrecords SET siteid = '".$siteid."', ip='".$ipaddress."', account='".$account."', date='".$time."', times='1' WHERE account='".$account."' AND siteid = '".$siteid."'") or die ('Error - Could not update vote records!');
}
$earnedpoints = true;
if ($earnedpoints == true) {
if ($account != '') {
$result = $mysqli->query("UPDATE accounts
SET $colvp = $colvp + $gvp,
$colnx = $colnx + $gnx
WHERE name='".$account."'") or die ('Error - Could not give rewards. Your site administrator needs to configure the NX and VP settings.');
}
$funct_msg = '<meta http-equiv="refresh" content="0; url='.$vsite['link'].'">';
$redirect = true;
}
} elseif($timecalc < $vsite['waittime'] && $row['amount'] != '') {
$funct_msg = 'You\'ve already voted for '.$vsite['name'].' within the last '.round($vsite['waittime']/3600).' hours!';
$funct_msg .= '<br />Vote time: '. date('M d\, h:i A', $row['date']);
} else {
$funct_error = 'Unknown Error';
}
}
}
if($redirect == true) {
echo $funct_msg;
} else {
if(isset($funct_msg)) {
echo '<div class="alert alert-danger">'.$funct_msg.'</div>';
}
if(isset($funct_error)) {
echo '<div class="alert alert-danger">'.$funct_error.'</div>';
}
$query = $mysqli->query("SELECT * from ".$prefix."vote");
if($query->num_rows == 0){
echo "<div class=\"alert alert-danger\">Your administrator has not added any voting sites yet!</div>";
} else {
echo "
<form method=\"post\">
<div class=\"form-group\">
<label for=\"voteSite\">Select Site:</label>
<select name=\"votingsite\" class=\"form-control\" id=\"voteSite\" required>
<option value=\"\" disabled selected>Select Site...</option>";
while($row = $query->fetch_assoc()){
echo "<option value=\"".$row['id']."\">".$row['name']."</option>";
}
echo "</select>
</div>";
if(!isset($_SESSION['id'])) {
echo "<input type=\"text\" name=\"name\" maxlength=\"15\" class=\"form-control\" placeholder=\"Username\" required autocomplete=\"off\"/><br/>";
} else {
echo "<input type=\"text\" name=\"name\" maxlength=\"15\" class=\"form-control\" placeholder=\"".$_SESSION['name']."\" value=\"".$_SESSION['name']."\" required autocomplete=\"off\"/><br/>";
}
echo "
<input type=\"submit\" name=\"submit\" value=\"Submit »\" class=\"btn btn-primary\"/>
</form>";
}
}
I have this in votingrecords table in SQL: ip, account, date, times, amount. It's correct.
The problem I'm having is that whenever I type my username to vote for the game, I'm getting this error message "Error - Could not look up vote record!".
Here's the code for this error:
else {
$result = $mysqli->query("SELECT *, SUM(times) as amount
FROM ".$prefix."votingrecords
WHERE NOT account=''
AND NOT account='0'
AND account='".$account."'
AND siteid = '".$siteid."'") or die('Error - Could not look up vote record!');
$row = $result->fetch_assoc();
$sitequery = $mysqli->query("SELECT * FROM ".$prefix."vote WHERE id = '".$siteid."'");
$vsite = $sitequery->fetch_assoc();
$gvp = $vsite['gvp'];
$gnx = $vsite['gnx'];
$timecalc = $time - $row['date'];
I hope you guys can help me, since I've tried everything and cannot get it to work
thanks for helping.
I got this issue fixed by executing this SET GLOBAL sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'; in MYSQL.
This would not happen if #RiggsFolly didn't tell me to use this code to display real useful errors, so thank you.
Thanks all!
I am trying to display a message when the search finds 0 results. I have tried several different ways to do it but nothing works; I always get a blank page or manage to display the message even when search finds results.
The code:
$post = $_POST;
if (isset($post['Kohderyhmä']) &&
isset($post['Näytön_aste']) &&
isset($post['Vaikutusten_vahvuus']) &&
isset($post['Käyttökelpoisuus']))
{
$Kohderyhmä = $post['Kohderyhmä'];
$Näytön_aste = $post['Näytön_aste'];
$Vaikutusten_vahvuus = $post['Vaikutusten_vahvuus'];
$Käyttökelpoisuus = $post['Käyttökelpoisuus'];
}
else
{
echo '<!-- Virhe -->'; /*die ('<h2>Ei hakutermiä syötetty. Avaa haku</h2>');*/
}
$count = 0;
$and = "";
$query = "";
if (!empty($Kohderyhmä) && $Kohderyhmä !="Kaikki" ) {
if ($count > 0) {
$and = " AND ";
}
$count++;
$query = $query.$and."`Kohderyhmä` LIKE '%".$Kohderyhmä."%'";
}
if (!empty($Näytön_aste) && $Näytön_aste !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Näytön aste` LIKE '%".$Näytön_aste."%'";
}
if (!empty($Vaikutusten_vahvuus) && $Vaikutusten_vahvuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Vaikutusten vahvuus` LIKE '%".$Vaikutusten_vahvuus."%'";
}
if (!empty($Käyttökelpoisuus) && $Käyttökelpoisuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Käyttökelpoisuus` LIKE '%".$Käyttökelpoisuus ."%'";
}
if ($count > 0) {
$query = "SELECT * FROM `tietokanta` WHERE ".$query;
} else {
$query = "SELECT * FROM `tietokanta`";
}
//echo $query;
if ($results = $conn->query($query)) {
while ($row = $results->fetch_assoc()) {
echo '<h3>' . $row['Nimi'] . '</h3>';
echo $row['Kokonaisarvio'] ."<br /><br />";
echo $row['Kuvaus'] ."<br /><br />";
}
} else {
echo '<h2>Haku ei tuottanut yhtään tulosta. Muuta hakuehtoja ja hae uudestaan.</h2>';
}
I have tried to find tutorials and other tips from the internet and php.net pages but I can't find a working solution.
That is quite strange because this question is asked every week. Not to mention you can read on mysqli_query's manual page that this function's return value is always positive, no matter whether it was found anything or not
Change your code to this
if ($results = $conn->query($query)->fetch_all(MYSQLI_ASSOC)) {
foreach ($results as $row) {
echo '<h3>' . $row['Nimi'] . '</h3>';
echo $row['Kokonaisarvio'] ."<br /><br />";
echo $row['Kuvaus'] ."<br /><br />";
}
} else {
echo '<h2>Haku ei tuottanut yhtään tulosta. Muuta hakuehtoja ja hae uudestaan.</h2>';
}
Try this following code
$results = $conn->query($query);
if ($results->num_rows >= 1){
while ($row = $results->fetch_assoc()) {
echo '<h3>' . $row['Nimi'] . '</h3>';
echo $row['Kokonaisarvio'] ."<br /><br />";
echo $row['Kuvaus'] ."<br /><br />";
}
}
else{
echo '<h2>Haku ei tuottanut yhtään tulosta. Muuta hakuehtoja ja hae uudestaan.</h2>';
}
I'm trying to print/echo values from previous file however instead of showing error, all that is shown is 'Undefined' on a blank page. I've researched and tried several method but nothing works. Please help.
<?PHP
$user_name = "root";
$password = "";
$database = "leadership_program";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
if (isset($_POST['survey_id'])) {
$survey_id = $_POST['survey_id'];
echo $survey_id;
}
if (isset($_POST['marks'])) {
foreach ($_POST['marks'] as $value) {
echo"$value";
}
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
echo $id;
}
// $SQL2 = "UPDATE answer_table SET marks='$value' WHERE survey_id= '$survey_id' AND student_id= '$id'";
//$result2 = mysql_query($SQL2);
//mysql_close($db_handle);
} else {
print "Database NOT Found ";
mysql_close($db_handle);
// header("Location: surveyView.php");
}
?>
Here is displayresult.php
<form action="student_mark_save.php" method="POST"> //<?php...more codes here
if ($strucrow["qns$i"] === 'radio' || $strucrow["qns$i"] === 'checkbox') {
foreach ($arr as $b) {
echo "<br/>";
if (strpos($b, '%#%') !== false) {
$c = substr($b, 3, -2);
//echo $c;
$d = str_replace("$arr[0] :-", ':', $c);
echo $d, "<br/>";
echo "<br/>";
echo "<tr> Marks : <input type=\"text\" name=\"marks[]\"></tr><br />";
//echo $b;
} else {
echo $b;
// echo "is not with comment qns";
}
}
} else if ($strucrow["qns$i"] === 'comment') {
foreach ($arr as $b) {
echo $b;
echo "<tr> Marks : <input type=\"text\" name=\"marks[]\"></tr><br />";
// echo "is not with comment qns";
}
} else {
}
echo "<p/>";
}
$marksquery = sprintf(
"SELECT marks FROM answer_table WHERE survey_id = '%d' AND student_id = '$studentid' ", mysql_real_escape_string($survey_id)
);
$marksQuer = mysql_query($marksquery) or die(mysql_error());
$marksrow = mysql_fetch_assoc($marksQuer);
echo "<td><input type=\"hidden\" value= \"$survey_id\" name=\"survey_id\"></td><br />" ;
echo "<td><input type=\"hidden\" value= \"$studentid\" name=\"id\"></td><br />" ;
echo "<p><input type=\"submit\" value=\"Update\"></p>";
?>
</form>
for undefined mean, there is something which is not existing in global $_POST[]
check try to print $_POST in your first if statement as:
if ($db_found) {
print_r($_POST);
exit();
if (isset($_POST['survey_id'])) {
$survey_id = $_POST['survey_id'];
echo $survey_id;
}
now just see what do you have in $_POST, It might help you...Thanks
Most likely some Post data is not set. Try vardump($_POST); die('happy');.
It would also be better to handle missing Post data instead of just ignoring it so maybe if ($db_found) { should be
<?php
if ( $db_found
&& isset($_POST['survey_id'])
&& isset($_POST['marks'])
&& isset($_POST['id'])
)
{
$survey_id = $_POST['survey_id']; //maybe ensure int
$id = $_POST['id']; //maybe ensure int
$values = array(); //this is important $value will not be available outside the for loop or contain only the last value
foreach ((array)$_POST['marks'] as $value) { //ensure $_POST['marks'] is an array
$values[] = $value; //maybe mysql escape each $value here
}
$SQL2 = sprintf(
"UPDATE answer_table SET marks='%s' WHERE survey_id=%d AND student_id=%d",
impolde(',' $values), //assuming comma separated list here
$survey_id,
$id
);
$result2 = mysql_query($SQL2);
mysql_close($db_handle);
} else { ...
Please also consider to escape the values you read from POST. Doing it this way makes it very easy to SQL inject into your script!
I'm trying to read a .CSV file and print it in a table format in HTML. At the end of the page is a comments text field where comments get submitted and saved in the database.
When I tested the code below locally it works fine. When I tried to run it on the linux server, it prints out fine when first opened, but when I press submit to save a comment, the page refreshes and the table does not print. Giving an "Invalid argument supplied for foreach()" error. (Note: this doesn't happen locally, i can submit all I want and it does not return an error.)
I've searched on stackoverflow and it seems that most of these problems are related to declaring the variable as an array. However, it seems odd to me as the code works fine the first time with no error, but once I submit it returns an error.
UPDATE: full code for file posted below.
<script>
window.onunload = refreshParent;
function refreshParent() {
window.opener.location.reload();
}
</script>
<?php
//---------------------------------Head/BG---------------------------------------
//Request Case ID
$case = "";
if(isset($_REQUEST['case'])) {
$case = $_REQUEST['case'];
}
$patientID = "";
if(isset($_REQUEST['patient'])) {
$patientID = $_REQUEST['patient'];
}
//Include basic functions to allow connection to SQL db.
include("generic.php");
//Include css and header information.
$printTitle = "Volume Report for Case ".$case."";
$printHeader = "Volume Report for Case ".$case."";
$printFooter = "";
$printBreadcrumb = "";
include("header.php");
//submit tableStatus update
if(isset($_REQUEST['submit'])) {
saveTableStatus($case);
}
//-----------------------------Start of Content----------------------------------
showStatusComment($case);
printVolumeTable($case,$patientID);
tableStatus($case);
//---------------------------End of Content--------------------------------------
//---------------------------Functions Definitions-------------------------------
//print report.csv Table
function printVolumeTable($case,$patientID){
echo "<html><body><table border='1'>\n\n";
$f = fopen("analyze/".$case."/".$patientID."/report.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "<tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
}
function showStatusComment($case) {
$connection = getMySqlConnection();
$sql = "SELECT p.STATUS_NAME, c.volume_comments FROM cases c, primary_status_lookup as p WHERE c.volume_status=p.STATUS_ID and c.caseid='".$case."'";
$result = mysql_query($sql, $connection) or die(mysql_error());
if($result!== FALSE){
while ($record = mysql_fetch_row($result)) {
$status=$record[0];
$comments=$record[1];
if($status == 'Clear Status') {$status = 'None'; $comments = 'None';}
print("<p><b>Table Status: </b>".$status." / <b>Comments: </b>".$comments."</p>");
}
}
}
//Status & Comments
function tableStatus($case) {
$connection = getMySqlConnection();
$sql = "SELECT volume_status, volume_comments FROM cases WHERE caseid='".$case."'";
$result = mysql_query($sql, $connection) or die(mysql_error());
if($result!== FALSE){
while ($record = mysql_fetch_row($result)) {
$status=$record[0];
$comments=$record[1];
print("<form><p>");
showStatusComment($case);
statusDropdown($case,$status);
print("<input type=hidden name='case' value='".$case."'/>");
print(" <label><b>Comments:</b><textarea name='comments' cols=70 rows=2 >".$comments."</textarea></label><br/><br/>");
print("<input type='submit' name='submit' value='Submit'/><INPUT type='button' value='Close Window' onClick='window.close()'></form>");
}
}
}
//Status Dropdown
function statusDropdown($case,$status){
print("<b>Status:</b>");
$dropdown = "<select name = 'status'><option selected='selected' value=NULL>--Select Status--</option>";
$connection = getMySqlConnection();
$sql = "SELECT STATUS_ID, STATUS_NAME FROM primary_status_lookup ORDER BY STATUS_ID ASC";
$result = mysql_query($sql, $connection) or die(mysql_error());
while($record=mysql_fetch_array($result)){
if ($status == '') {
$dropdown .= "<option value = '{$record['STATUS_ID']}'> {$record['STATUS_NAME']}</option>";
} else if (($status == $record['STATUS_ID']) && ($status == '99')) {
$dropdown .= "<option value = '{$record['STATUS_ID']}'> {$record['STATUS_NAME']}</option>";
} else if ($status == $record['STATUS_ID']) {
$dropdown .= "<option value = '{$record['STATUS_ID']}' selected='selected'> {$record['STATUS_NAME']}</option>";
} else {
$dropdown .= "<option value = '{$record['STATUS_ID']}'> {$record['STATUS_NAME']}</option>";
}
}
$dropdown .="</select>";
echo $dropdown;
}
function saveTableStatus($case)
{
//retrieve selected status
$status = '';
if(isset($_REQUEST['status'])) {
$status = $_REQUEST['status'];
}
//retrieve typed comments
if(isset($_REQUEST['comments'])) {
$comments = $_REQUEST['comments'];
}
if($status=='NULL') {
print("<p class='error'>No status selected, please select a status and try again.</p>");
}
else if (($status!=='NULL')){
$connection = getMySqlConnection();
mysql_query("START TRANSACTION", $connection);
if ($status =='99') {$comments = '';}
$result= mysql_query("Update cases Set volume_status=".$status.", volume_comments ='".mysql_real_escape_string($comments)."' Where caseid='".mysql_real_escape_string($case)."'", $connection);
if($result) {
mysql_query("COMMIT", $connection);
print("<p class='saved'>Table Status Updated!</p>");
} else {
mysql_query("ROLLBACK", $connection);
}
mysql_close($connection);
}
}
?>
If you form, and the script that takes the posted form are not on the same path, then your
$f = fopen("analyze/".$case."/".$patientID."/report.csv", "r");
will not open the same file.
Edit -
Okay I think your problem is your $case variable. If there is no request, the $case is blank (""). So the above line will open "analyze///report.csv" As you can see depending on this code
$case = "";
if(isset($_REQUEST['case'])) {
$case = $_REQUEST['case'];
}
I have a html form tat my user can use to search through a table in my MYSQL database.
By default if you just hit go it will display the entire table, however I would like them to be able select certain fields and my php form to search via the fields that are filled in.
I seem to be unable to find a way of doing this without writing a seperate query for all 11 inputs in the different combinations they could be entered in, which comes out at a total of 76 queries..
If anyone has a way to simplify this I would love any advice.
I have tried just running a query with the AND operator but that doesnt work as some variables can be left empty and that will return no result, not sure if that is what is upposed to happen, but that is what is happening.
my html and php:
http://jsbin.com/oquwid/1/edit
PHP
$sql = "SELECT * FROM ".$tbl_name."
WHERE fname='".$fname."'
and lname='".$lname."'
and city='".$city."'
and phone='".$pohne."'
and interest_inet='".$internet."'
and interest_tv='".$television."'
and interest_voice='".$voice."'
and submission_ip='".$ip."'
and inquiry_handled='".$handled."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
echo $row;
}
echo "</table>";
You could append parts to the query depending on which are filled in:
if(!empty($fname) || !empty($lname) || !empty($city) || etc.etc.) {
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryParts = array();
if($fname != "") {
$queryParts[] = " fname='$fname'";
}
if($lname != "") {
$queryParts[] = " lname='$lname'";
}
etc.etc.
$sql .= implode(" AND ", $queryParts);
// do query, etc.
}
else {
// Don't do query if no parameters are specified
}
You also need to make sure that you escape all of your query parameters before you use them or risk having someone ravage your data.
The following uses loops to avoid duplicate code:
$fieldIsSpecified = false;
$queryFields = array('fname' => $fname, 'lname' => $lname, 'city' => $city, etc...);
foreach($queryFields as $column => $value) {
if(!empty($value){
$fieldIsSpecified = true;
break;
}
}
if($fieldIsSpecified) {
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryParts = array();
foreach($queryFields as $column => $value) {
if(!empty($value)) {
$queryParts[] = " $column = '$value'";
}
}
$sql .= implode(" AND ", $queryParts);
// do query, etc.
}
else {
// Don't do query if no parameters are specified
}
The reason you're query isn't working if a value is not filled in, is probably because the query results in this (given first name is empty)
SELECT * FROM $tbl_name WHERE fname=''
And there probably isn't a user having no first name.
Further, you considered adding a flag per requested info, and on base of that either add or remove the needed part to the select part of the query ?
For example,
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryChanged = false;
if (isset($fname)){
if (!empty($fname)){
$sql .= "fname='$fname' ";
$queryChanged=true;
}
}
if (isset($lname)){
if (!empty($lname)){
$sql .= ($queryChanged) ? " AND lname='$lname'" : "lname='$lname'";
$queryChanged = true;
}
}
... //Continue the logic
I'd recommend you to read this post about select * as well as this about user input and how to handle it
this is how i am going to have to do it
php:`
//if just lname is set
if(empty($start_date) && empty($end_date) && empty($fname) && isset($lname) && empty($city) &&
empty($internet) && empty($television) && empty($voice) && empty($phone) && empty($ip) &&
empty($handled) && empty($not_handled)){
$sql = "SELECT * FROM ".$tbl_name."
WHERE lname='".$lname."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
}
echo "</table>";
exit();
}
//if just city is selected
if(empty($start_date) && empty($end_date) && empty($fname) && empty($lname) && isset($city) &&
empty($internet) && empty($television) && empty($voice) && empty($phone) && empty($ip) &&
empty($handled) && empty($not_handled)){
$sql = "SELECT * FROM ".$tbl_name."
WHERE city='".$city."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
}
echo "</table>";
exit();
}
And etc... i am going to have to repeat this process until i cover all, 76 i believe, possibilites. thnkfully its just a lot of copy paste. thanks for the help everyone
First don't use MYSQL_*. Use PDO
Second, with your code, your are requiring all fields to be filled.
If you don't wanna do that then go this way:
You can use WHERE 1=1 , but it's not recommended !!!!!
$sql = "SELECT * FROM ".$tbl_name." WHERE confirm = '0' ";
$sql .= "AND fname = ".$fname."";
$sql .= "AND lname = ".$lname."";
$sql .= "AND city = ".$city."";
$sql .= "AND phone = ".$pohne."";
$sql .= "ORDER BY date DESC";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
echo $row;
}
echo "</table>";