Switch function outputting default instead of desired value - php

I'm trying to do a simple switch function with the following code.
$query = "SELECT * FROM entries where Venue='Condamine' and Year='2018' and
Event='$5,000 Novice' and herd='2' and scratched IN('n','l') ORDER BY Draw
ASC";
// Execute the query
$result = mysqli_query($con ,$query);
if (!$result){
die ("Could not query the database: <br />". mysqli_error());
}
// Change herds
function getherd($catch) {
switch($catch)
{
case '2':
return 'Herd Change';
break;
default:
return 'Damn!';
break;
}
}
$catch = $row["herd"];
echo "<tr>";
echo "<td bgcolor=#FFFFFF><strong> ". getherd($catch) ." </strong></td>";
echo "<td bgcolor=#FFFFFF> </td>";
echo "</tr>";
?>
My result is printing out the default value "Damn!" instead of the desired value "Herd Change" what am I doing wrong. I want to print out the words "Herd Change" if the value of the row herd = 2.

its most probably a typecasting issue
try
$catch = string($row["herd"]); and make sure the $catch is 2

Your code should be changed as below.
<?php
$query = "SELECT * FROM entries where Venue='Condamine' and Year='2018' and
Event='$5,000 Novice' and herd='2' and scratched IN('n','l') ORDER BY Draw
ASC";
// Execute the query
$result = mysqli_query($con ,$query);
if (!$result){
die ("Could not query the database: <br />". mysqli_error());
}
// Change herds
function getherd($catch) {
switch($catch)
{
case '2':
return 'Herd Change';
break;
default:
return 'Damn!';
//Break doesn't require in default case
}
}
//here you need to get results set from $result.
$html = "";
while ($row = mysqli_fetch_row($result)) {
$catch = $row["herd"];
$html += "<tr>";
$html += "<td bgcolor=#FFFFFF><strong> ". getherd($catch) ." </strong></td>";
$html += "<td bgcolor=#FFFFFF> </td>";
$html += "</tr>";
}
echo $html;
//It will print multiple rows, If query returns multiple rows.
?>

If your variable $catch contains integer value then use below syntax.
switch($catch){
case 2:
// your code
default:
// your code
}
In case of String value do the following,
switch($catch){
case "2":
// your code
default:
// your code
}
Switch case manual
It is not good practice to manually typecast the variable.
I hope it helps!

Related

mysql echo if no resuts found

If there is data the first part works great. When there are no $res the else portion is not echoing.
IO have tried using this but the ! $row stops and will not echo anything inside. so I rewrote it to the php script below which is more straight forward. I was now that worried about sql injection since I am cleaning id as well as verifying the user is actually logged into the system.
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if( ! $row)
{
die('nothing found');
}else {
enter code here
}
Thjs is my entire php page.
$db = new PDO (connection string. )
<?php
error_reporting(0);
include_once("php_includes/db_conx.php");
if($_GET['id'] != ''){
$id = preg_replace('#[^0-9]#', '', $_GET['id']);
$sql="SELECT nextdue, alert, completed, page_id, page_type FROM medical where id=$id limit 1";
$alertdiv = "";
if ($res = $db->query($sql)) {
$alertdiv = "";
foreach( $db->query($sql) as $data ) {
//if alert is set to Y create div to show the type and stuff.
$timestamp = $data[0];
if ($data[1]=='y'){
if($timestamp > date("Y-m-d")) {
$alertdiv .= "This alert is in the Future.<br>";
}
if($timestamp < date("Y-m-d")) {
$alertdiv .= "This alert is pastdue.<br>";
}
if($timestamp == date("Y-m-d")) {
$alertdiv .= "This alert is due Today.<br>";
}
$alertdiv .= "<table><tr><td width='50'>Method</td><td>Description</td><td>Destination</td><td>Completed</td><td>Date Due</td><td>Action</td></tr><br>";
$completed = $data[2];
$page_id = $data[3];
$page_type = $data[4];
//check completed
//get page details
switch ($page_type) {
case "d":
$alertdiv .= "<tr id='selectedmethodtr' value='d0'>";
$alertdiv .= "<td width='10'>Default</td><td>Dashboard</td><td>Dashboard</td>";
break;
case "e":
$alertdiv .= "<tr id='selectedmethodtr' value='e$data[3]'>";
$sql1 = "SELECT description, email from page_email where page_email_id=$page_id";
foreach( $db->query($sql1) as $data1 ) {
$alertdiv .= "<td width='50'>E-Mail</td><td>$data1[0]</td><td>$data1[1]</td>";
}
break;
case "p":
$alertdiv .= "<tr id='selectedmethodtr' value='p$data[3]'>";
$sql1 = "SELECT description, phone, carriervalue from page_phone where page_phone_id=$page_id";
foreach( $db->query($sql1) as $data1 ) {
$alertdiv .= "<td width='50' >E-Mail</td><td>$data1[0]</td><td>$data1[1]</td>";
}
break;
}
switch ($completed) {
case "0":
$alertdiv .= "<td>No</td>";
break;
case "1":
$alertdiv .= "<td>Yes</td>";
break;
}
$alertdiv .= "<td>$timestamp</td>";
$alertdiv .= "<td><a onClick=deleteAlert($id) id='deleteAlert'><i class='fa fa-trash-o fa-lg'></i></a></td></tr>";
}
}//end if data[1]
$alertdiv .= "</table>";
echo $alertdiv;
}else {
$alertdiv .= "Alert Type is set Default Dashboard! <br>";
$alertdiv .= "<table id='selectedmethodtable'>";
$alertdiv .= "<tr>";
$alertdiv .= "<td>Description</td>";
$alertdiv .= "<td >Method</td><option id='selectedmethodtr' value='d0' ></option>";
$alertdiv .= "</tr>";
$alertdiv .= "<tr ><td>DashBoard</td><td>Default</td></tr>";
$alertdiv .= "</table>";
echo $alertdiv;
}
}
?>
Your comments ("found results") are wrong.
I'm assuming that $db->query is mysqli's query method.
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
It is a true value if the query ran successfully, even if that query found no matching rows.
You'll get a false result if there was an error running the query.
To test if there are no results, you should use num_rows.
if ($res = $db->query($sql)) { // Query ran without errors
if ($res->num_rows == 0) {
// There were no results found
} else {
while($row = $res->fetch_assoc($result)) {
// Do stuff with the data in the `$row`
}
}
} else {
// There was an error running the query
}

how do i display this columns side by side

im having some problem here. basically, i want to compare columns. so i fetched object and the comparing results appeared just as expected. however, it does not return the compare value anymore after i added the fetch_array to view the current table hoping that the compare value would appear beside the compare value. is there any way i could run the compare code and make it appear the table? i tried a query but it would only work in MySQL and not PHP.
$query = "SELECT * FROM system_audit"; $result = mysql_query($query) or die(mysql_error());
echo " ID Type Setting Value ";
while($row = mysql_fetch_array($result)) {
echo $row['ID'];
echo $row['Type'];
echo $row['Setting'];
echo $row['Value'];
}
while ($row = mysql_fetch_object($result)) {
if($row->Setting != $row->Value) {
echo "X";
} else {
echo "O";
}
}
Your code contains a lot of echo's that have no use. I would suggest learning PHP a bit more.
Your compare is wrong, this should work :
$query = "SELECT * FROM system_audit";
$result = mysql_query($query) or die(mysql_error());
echo " ID Type Setting Value ";
while($row = mysql_fetch_array($result)) {
echo $row['ID'] . "<br>";
echo $row['Type'] . "<br>";
echo $row['Setting'] . "<br>";
echo $row['Value'] . "<br>";
if($row['Setting'] != $row['Value']) {
echo "X" . "<br>";
}
else {
echo "O" . "<br>";
}
echo "<br>";

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;

Updating multiple SQL records using a single submit button

Scenario: I have multiple text boxes in which a user will enter data into some of them / all of them / or none of them.
Goal: I need to be able to UPDATE multiple records based on what is in the text boxes where the users has entered their data.
Problem: The update statement is not working when I try to update each record for each text box.
Below is the code:
$conn = mysql_connect ($localhost, $user, $pass);
mysql_select_db($db_name, $conn) or die (mysql_error());
$myFile = "/var/www/html/JG/LSP/lsp_ref.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
if (isset($_POST['submit'])) {
foreach ($_POST['notes'] as $key=>$value) {
echo $_POST['notes'][$key];
#echo "<br/>";
//echo "$key";
//echo "<br/>";
$query_update = "UPDATE lsp_active SET Notes = ".$_POST['notes'][$key];
$result_update = mysql_query($query_update);
}
#header ('Location:lsp_display.php');
}
$query = "SELECT * FROM lsp_active";
$result = mysql_query($query);
$field_num = mysql_num_fields($result);
echo "<form method='post' action='lsp_display.php'>";
echo "<table border=1>";
$cols = 0;
while ($row = mysql_fetch_assoc($result)) {
if ( $cols == 0) {
$cols = 1;
echo "<tr>";
foreach ($row as $col => $value) {
print "<th>$col</th>";
}
print "<th>Insert Ticket / Notes</th>";
echo "</tr>";
}
echo "<tr>";
foreach ($row as $cell) {
echo "<td>$cell</td>";
}
echo "<td><input type='text' name='notes[]'/></td>";
echo "</tr>\n";
}
echo "<tr><td colspan=8><input type='submit' name='submit' value='Update'/></td></tr>";
echo "</form>";
mysql_free_result($result);
?>
Now when I print out $_POST['notes'][$key] it spits back out what I give it in the text boxes.
However, the update statement that I have for my SQL isn't updating the database with what I put in.
I am not sure what could be wrong with it :(.
Any help is appreciated!
Thank you!
It looks like you probably need to surround your $_POST in single quotes.
Also use a function to clean the $_POST variable.
For example:
function escape($data) {
$magicQuotes = get_magic_quotes_gpc();
if(function_exists('mysql_real_escape_string')) {
if($magicQuotes) {
$data = stripslashes($data);
}
$data = mysql_real_escape_string($data);
}
else {
if(!$magicQuotes) {
$data = addslashes($data);
}
}
return $data;
}
And then your query:
$query_update = "UPDATE lsp_active SET Notes = '" . escape($_POST['notes'][$key]) . "'";
Edit:
You also might want to put a WHERE statement on the end of your UPDATE query, so that you don't update everything in the table.
"UPDATE lsp_active a SET a.Notes = '" . mysql_real_escape_string($_POST['notes'][$key]) ."' WHERE a.Index = '" . ($key + 1). "'"
Index is a keyword thar refers to indexes, not your column. So I defined an alias, and made it explicit that Im referring to the column. Also, the + 1 on the Where $key since Index is not zero-based like PHP arrays.

Echo items with value of three

I need to echo all items in my column that have the value of three. If a field has the value of three I then need to echo the 'name' and 'description' on that row.
This is what I have so far
$result = mysql_query($query1) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['status'];
}
I need to write 'if $row[`status´ == 3 echo 'description' 'name' else echo 'no current staus'
I hope I made some sense because I am seriously confused
You can actually select the result which only has 3 value in its status
for that use this
$query = "SELECT * FROM yourtable WHERE status='3'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array(result)) {
echo "Name: ".$row['name']."<br>Description: ".$row['description'];
}
and if you want to parse you result to display only those of value this then use this
$query = "SELECT * FROM yourtable";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array(result)) {
if($row['status']==3) {
echo "Name: ".$row['name']."<br>Description: ".$row['description'];
}
}
if $row['status'] == 3 {
echo ($row['description']." ".$row['name']);
}
else
{
echo ('no current staus');
}
The "." in the first echo means string concatenation. I'm separating description and name with a single space character, feel free to change this.
I'm expecting something more since you have the "i need to write" part that is the answer?
$result = mysql_query($query1) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) // fetch_assoc better for your case
{
if( $row['status'] == 3 ) {
echo $row['description'];
}else {
echo 'no current staus';
}
}
For the sake of info for tasks with a numeric status
switch( $row['status'] ) {
case 0:
// do something
break;
case 1:
// do something
break;
case 2:
// do something
break;
case 3:
// do something
break;
default:
echo 'No status set';
}
if ($row['status'] == 3) {
echo $row['name'];
echo $row['description'];
}
$result = mysql_query($query1) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
if ($row['status'] == 3) {
echo $row['name'] . ' - ' . $row['description'];
}
else {
echo 'no curent status';
}
}
if($row['status']==3) {
echo $row['description'];
echo $row['name'];
} else {
echo 'no current status';
}
Maybe you should learn about basics of PHP and algorithms and make sure you understand this, before you move on.
This?
$result = mysql_query($query1) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
if (!in_array(3, $row['status']))
{
echo 'no current staus';
break;
}
echo $row['description'] . <br />;
echo $row['name'] . <br />;
}
or you could use SQL to select the values for you...
$query1 = SELECT * FROM table WHERE column = '3';
$result = mysql_query($query1) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['status'];
}

Categories