Page authentication doesn't work - php

This code is from O'Reilly Head First PHP&MySQL book. The script doesn't recognize the username and password somehow:
<?php
$username = 'rock';
$password = 'roll';
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) ||
($_SERVER['PHP_AUTH_USER'] != $username) || ($_SERVER['PHP_AUTH_PW'] != $password)) {
// The user name/password are incorrect so send the authentication headers
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Guitar Wars"');
exit('<h2>Guitar Wars</h2>Sorry, you must enter a valid user name and password to access this page.');
}
?>
And this is the script, from which the authentication file is required:
<?php
require_once('authorize.php');
?>
<!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>Guitar Wars - High Scores Administration</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h2>Guitar Wars - High Scores Administration</h2>
<p>Below is a list of all Guitar Wars high scores. Use this page to remove scores as needed.</p>
<hr />
<?php
require_once('appvars.php');
require_once('connectvars.php');
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Retrieve the score data from MySQL
$query = "SELECT * FROM guitarwars ORDER BY score DESC, date ASC";
$data = mysqli_query($dbc, $query);
// Loop through the array of score data, formatting it as HTML
echo '<table>';
echo '<tr><th>Name</th><th>Date</th><th>Score</th><th>Action</th></tr>';
while ($row = mysqli_fetch_array($data)) {
// Display the score data
echo '<tr class="scorerow"><td><strong>' . $row['name'] . '</strong></td>';
echo '<td>' . $row['date'] . '</td>';
echo '<td>' . $row['score'] . '</td>';
echo '<td><a href="removescore.php?id=' . $row['id'] . '&date=' . $row['date'] .
'&name=' . $row['name'] . '&score=' . $row['score'] .
'&screenshot=' . $row['screenshot'] . '">Remove</a>';
if ($row['approved'] == '0') {
echo ' / <a href="approvescore.php?id=' . $row['id'] . '&date=' . $row['date'] .
'&name=' . $row['name'] . '&score=' . $row['score'] . '&screenshot=' .
$row['screenshot'] . '">Approve</a>';
}
echo '</td></tr>';
}
echo '</table>';
mysqli_close($dbc);
?>
</body>
</html>
Can you see what's wrong here?
Thank you!

The authentication code is perfectly fine.
You might have extra spaces (before <?php) or something else there before the header() calls.. in that case you don't see the authentication popup.

Related

get id from buttons with same name in php

So I have a website that runs a cycle on a database as long as there is a record in it.
It also puts two buttons in each row within the table.
Each button has the same name.
If I press one of the buttons, how can I get the ID of that button (which points to a Youtube link from the database) to be included in a SQL query.
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ruben MediaShare</title>
</head>
<body>
<form method='POST'>
<?php
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['modname'] . "!";
} else {
echo "Please log in first to see this page.";
}
$link = mysqli_connect("localhost", "asd", "asd", "mediareq");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM requests";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>link</th>";
echo "<th>Twitch Név</th>";
echo "<th>Üzenet</th>";
echo "<th>Engedélyezés</th>";
echo "<th>Elutasítás</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
$link = $row['link'];
echo "<td>" . "<iframe width='560' height='315' src='$link' frameborder='0' allowfullscreen></iframe>" . "</td>";
echo "<td>" . $row['ttvname'] . "</td>";
echo "<td>" . $row['msg'] . "</td>";
echo "<td>" . "<input type='submit' id='$link' value='' name='enable'></input>" . "</td>";
echo "<td>" . "<input type='submit' id='$link' value='' name='eject'></input>" . "</td>";
echo "</tr>";
}
mysqli_free_result($result);
if (isset($_POST['enable'])) {
$ID = $_POST[$link];
echo $ID;
}
} else{
echo "Még nem kaptál videót, várjál már egy kicsit vagy csak tolj egy F5öt Pog Pog Pog";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
</form>
</body>
</html>
The website looks like this: https://imgur.com/a/MWVj7L5
If it can't be done that way, what can I do in this case to keep the loop but since it has to be dynamic, and somehow get it to pick the link from each button that it stores in the ID (or some other way)

use SQL data selected from html dropdown list

NEWBIE ALERT
Ive been reading for hours but cannot see how to do what I want. I have an SQL DB with a list of medication and dosages etc. Im trying to create an 'edit' page so i can select the medication from a dropdown list(this appears to work), and edit certain parts of it(size, box quantity, doseage etc.
the problem is i cant get the selected medication item(from dropdown) to become a variable or if neccessary, forward to a 2nd PHP page.
Ive left a couple of attempted edits in there but they caused errors (TRIED NOT WORK)
As it is, It is loading editmed.php to load my edit page on submit. (not sure if this is the best way of doing it).
Any help would be great thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Editor</title>
<link rel="stylesheet" href="global.css">
</head>
<body>
<div class="header">
<h1>Edit Medication Item</h1>
</div>
<div class="topnav">
Home
<a class="active" href="edit.php">Edit Medication</a>
Prescription Collection
Add New Medication
Pillbox refill
Individual refill
</div>
<?php
// server connect
$mysqli = new mysqli("localhost:port", "USERNAME", "PASSWORD", "prescription")
or die ('Cannot connect to db');
// select medication name field from db
echo "<p><b><U><i><p style='color:red'>Select Medication</I></U></p><p style='color:black'></b></p>";
$sqlSelect="select Medication from general";
$result = $mysqli -> query ($sqlSelect);
//$medselect=$result['Medication'];**TRIED NOT WORK**
echo "<form action='editmed.php'>";
echo "<select id=`Medication` name=`medselect`>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['Medication'] . "'>" . $row['Medication'] . "</option>";
}
//$medselect=$result['Medication'];**TRIED NOT WORK**
echo "</select>";
echo "<input type='submit' value='submit'>";
// echo "<input type='submit' value='<$medselect>' name='medselect'/>" ; **TRIED NOT WORK**
echo "</form>" ;
echo "</body>";
echo "</html>";
?>
</body>
</html>
editmed.php >
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Editor</title>
<link rel="stylesheet" href="global.css">
</head>
<body>
<div class="header">
<h1>Edit Medication Item</h1>
</div>
<div class="topnav">
Home
<a class="active" href="edit.php">Edit Medication</a>
Prescription Collection
Add New Medication
Pillbox refill
Individual refill
</div>
<?php
// server connect
$link = mysqli_connect("localhost:port", "user", "password",
"prescription")
or die ('Cannot connect to db');
// $sql = "SELECT ID, Medication, dosagedaily, Box_Size, Boxed_remain,
grandtotal, last_collected, Dosage, countdown FROM general where
`Medication` = $medselect";
$sql = "SELECT ID, Medication, dosagedaily, Box_Size, Boxed_remain,
grandtotal, last_collected, Dosage, countdown FROM general where
`Medication` = 'Esomeprazole 40mg'";
// you check sql and link true
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>Index</th>";
echo "<th>Medication</th>";
echo "<th>Daily Dosage</th>";
echo "<th>Box Size</th>" ;
echo "<th>Boxed Remaining</th>" ;
echo "<th>Grand Total</th>";
echo "<th>Last presc collection</th>";
echo "<th>Dosage</th>";
echo "<th>Pills Remaining</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Medication'] . "</td>";
echo "<td>" . $row['dosagedaily'] . "</td>";
echo "<td>" . $row['Box_Size'] . "</td>";
echo "<td>" . $row['Boxed_remain'] . "</td>";
echo "<td>" . $row['grandtotal'] . "</td>";
echo "<td>" . $row['last_collected'] . "</td>";
echo "<td>" . $row['Dosage'] . "</td>";
echo "<td>" . $row['countdown'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
i dont know how to assign the variables from the input form, thats where my issue is.If i get a variable assigned then i can create the actual editing part.

ISNULL from Mysql not showing Results on webpage via PHP

I'm working on a server based POS and I have a php page that displays the client current money on a table, I have 2 tables (Mov_ctes and Clientes), it works fine when I add WITH ROLLUP on the mysql query, It displays the Total but without A Name (NULL value), so I used
IFNULL(Clientes.Nombre,'TOTAL')
so It could change the NULL value to TOTAL, I entered the whole command on mysql and worked fine, however if I enter the same query via PHP it doesnt output the "Nombre" column
heres my code and a Mysql screenshot
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
<!--
#import url("source/style.css");
-->
</style>
</head>
<body>
<?php
session_start();
$log=$_SESSION['sesion'];
$nombr=$_SESSION['username'];
if($log==1)
{
$con=mysqli_connect("localhost","user","pw","My_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Mysql query
$result = mysqli_query($con,"SELECT Clientes.cliente_id,IFNULL(Clientes.Nombre,'TOTAL'), sum(Mov_ctes.Movimiento) FROM Clientes NATURAL LEFT JOIN Mov_ctes GROUP BY Nombre WITH ROLLUP");
echo "<table id='hor-minimalist-b' summary='Employee Pay Sheet'>";
echo "<thead>";
echo "<tr>";
echo "<th scope='col'>ID</th>";
echo "<th scope='col'>Nombre</th>";
echo "<th scope='col'>Saldo</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = mysqli_fetch_array($result))
{echo "<tr>";
echo "<td>" . $row['cliente_id'] . "</td>";
echo "<td>" . $row['Nombre'] . "</td>";
echo "<td>" . $row['sum(Mov_ctes.Movimiento)'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
mysqli_close($con);
}
?>
You need an alias for the column, otherwise the column name will be IFNULL(Clientes.Nombre,'TOTAL'):
SELECT IFNULL(Clientes.Nombre,'TOTAL') AS Nombre
...

Session to echo a row retrieved from database

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 :)

Rails: printing mysql query

I cant figure out how to display MySql information using Ruby on Rails.
This is the query i want to run
SELECT name, description FROM projects where status > 1
If someone can translate to Rails the code below it would be greatly apreciatted
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Proyects</title>
</head>
<?php
$dsn = "mysql:dbname=redmine_default";
$username = "root";
$password = "";
try {
$conn = new PDO( $dsn, $username, $password );
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo "Error: " . $e->getMessage();
}
function mostrarProyectos($conn) {
$sql = 'SELECT * FROM projects';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
print $row['id'] . "\t";
print $row['description'] . "\n";
}
}
//creating a table with 4 columns
?>
<table border="1" cellspacing=1 cellpadding=2 style="font-size: 8pt"><tr>
<td><font face="verdana"><b>ID</b></font></td>
<td><font face="verdana"><b>Name</b></font></td>
<td><font face="verdana"><b>Status</b></font></td>
<td><font face="verdana"><b>Desc</b></font></td>
</tr>
<?php
//here comes the SQL query
$query = "SELECT name, description FROM projects where status > 1";
$resultado = $conn->query($query);
$numero = 0;
foreach($resultado as $row)
{
echo "<tr><td width=\"25%\"><font face=\"verdana\">" .
$row["id"] . "</font></td>";
echo "<td width=\"25%\"><font face=\"verdana\">" .
$row["name"] . "</font></td>";
echo "<td width=\"25%\"><font face=\"verdana\">" .
$row["status"] . "</font></td>";
echo "<td width=\"25%\"><font face=\"verdana\">" .
$row["description"]. "</font></td></tr>";
$numero++;
}
echo "<tr><td colspan=\"15\"><font face=\"verdana\"><b>N&uacutemero: " . $numero .
"</b></font></td></tr>";
mysql_free_result($result);
mysql_close($link);
?>
</table
</body>
</html>
The RoR code would be something like this:
Project.where("status > ?", 10)
http://guides.rubyonrails.org/active_record_querying.html
The link will give you a large list of mysql queries and their RoR counterpart.

Categories