Session to echo a row retrieved from database - php

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

Related

PHP create button whit mySql DB

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 } ?>

Output database variable with multiple line breaks

I've read about the nl2br() command but they echo out the variable to make it work but my variable is inside a list that I echo out.
Should I somehow put the nl2br() command in my if statement where I'm setting up the output or should I be looking somewhere else for my answer.
I have made 2 extra detail variables to output so I get 3 lines of text for the description of my product but there has to be a better way of doing it than that. I would think 1 detail variable with all the info would be the preferred way of doing it
I have tried to search for it but I'm afraid I'm just not asking the right question so any help in the right direction is appreciated.
<?php require_once './connections/connect_mysqli.php';
$conn = dbConnect('read');
$sql = "SELECT * FROM products ORDER BY id ASC LIMIT 6 ";
$result = $conn->query($sql) or die($conn->error);
$i = 0;
$flatlist = "";
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$details = $row["details"];
$details2 = $row["details2"];
$details3 = $row["details3"];
$price = $row["price"];
if ($i % 4 == 0) {
$flatlist .='<tr><td width="250px" align="center"><img src="images/' . $id . '.jpg"><br/>
<p style=color:blue font-size=14px;>' . $product_name . '</p><br/>
<p style=font-size:14px;>' . $details . '</p><br />
' . $details2 . '<br />
' . $details3 . '<br />
<p style=font-size:14px;>$' . $price . '</p><br />
<input type="button" value="Order" style=color:blue></td>';
} else {
$flatlist .= '<td width="250px" align="center"><img src="images/' . $id . '.jpg"><br/>
<p style=color:blue font-size=14px;>' . $product_name . '</p><br />
<p style=font-size:14px;>' . $details . '</p><br />
' . $details2 . '<br />
' . $details3 . '<br />
<p style=font-size:14px;>$' . $price . '</p><br />
<input type="button" value="Order" style=color:blue></td>';
}
$i++;
}
$flatlist .= '</tr></table>';
?>
<!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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flats</title>
</head>
<body>
<?php require 'includes/skyline.php'; ?>
<?php require 'includes/menu.php'; ?>
<table width="1200" border="0" align="center">
<tr>
<?php echo $flatlist ?>
</tr>
</table>
<?php require 'includes/footer.php';?>
Want to point out you close the details <p> before the 2nd and 3rd lines. You probably want to close that after third line.
<p style=font-size:14px;>' . $details . '<!-- remove here: </p> --><br />
' . $details2 . '<br />
' . $details3 . '<br /><!-- add here: --></p>
If you keep your same database structure, you can define into one variable after retrieving like:
$details = $row["details"] . '<br/>' . $row['details2'] . '<br/>' . $row['details3'];
And then just refer back to $details later on.
Why don't you want to use nl2br()? This would allow you to store multiple lines all into details column. Then you would just use:
$details = nl2br( $row["details"] );`
Here are my edits to your code:
<?php require_once './connections/connect_mysqli.php';
$conn = dbConnect('read');
$sql = "SELECT * FROM products ORDER BY id ASC LIMIT 6 ";
$result = $conn->query($sql) or die($conn->error);
$i = 0;
$flatlist = "";
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$details = $row["details"] . '<br/>' . $row['details2'] . '<br/>' . $row['details3'];
$price = $row["price"];
if ($i % 4 == 0) {
$flatlist .='<tr><td width="250px" align="center"><img src="images/' . $id . '.jpg"><br/>
<p style=color:blue font-size=14px;>' . $product_name . '</p><br/>
<p style=font-size:14px;>' . $details . '</p><br />
<p style=font-size:14px;>$' . $price . '</p><br />
<input type="button" value="Order" style=color:blue></td>';
} else {
$flatlist .= '<td width="250px" align="center"><img src="images/' . $id . '.jpg"><br/>
<p style=color:blue font-size=14px;>' . $product_name . '</p><br />
<p style=font-size:14px;>' . $details . '</p><br />
<p style=font-size:14px;>$' . $price . '</p><br />
<input type="button" value="Order" style=color:blue></td>';
}
$i++;
}

implode in where class

I am having a problem with array while using it in "select" statement
that array contains the following strings
Array
(
[0] => M.A.JINNA
[1] => K.DHANA RAJU
[2] => B.EPHRIM
)
array data had came from the following data
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<style>
table{
border : 1px solid black;
}
tr{
border : 1px solid black;
}
td{
border : 1px solid black;
}
</style
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Update Deployement</title>
<style type="text/css">
body
{
background-color: #00FF00;
background-image: url(images/gail-india.jpg);
color: #000000;
scrollbar-face-color: #0B0B0B;
scrollbar-arrow-color: #C8C8C8;
scrollbar-3dlight-color: #0B0B0B;
scrollbar-darkshadow-color: #000000;
scrollbar-highlight-color: #141414;
scrollbar-shadow-color: #060606;
scrollbar-track-color: #0B0B0B;
}
</style>
</head>
<body>
<form method="post" action="edit_data.php">
<div id="wb_Image3" style="margin:0;padding:0;position:absolute;left:7px;top:4px;width:208px;height:129px;text-align:left;z-index:0;">
<img src="images/image_thumb3.png" id="Image2" alt="" border="0" style="width:208px;height:129px;"></div>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("gail", $con);
$installation_1 = trim($_POST['installation']);
$area_1 = trim($_POST['area']);
$district_1 = trim($_POST['district']);
if(empty($area_1) AND empty($district_1))
{
$sql = "SELECT * FROM deployment WHERE installation ='" . $installation_1 . "'";
}
else if(empty($installation_1) AND empty($district_1))
{
$sql = "SELECT * FROM deployment WHERE area ='" . $area_1 . "'";
}
else if(empty($installation_1) AND empty($area_1))
{
$sql = "SELECT * FROM deployment WHERE district ='" . $district_1 . "'";
}
else if(empty($district_1))
{
$sql = "SELECT * FROM deployment WHERE installation ='" . $installation_1 . "' AND area ='" . $area_1 . "'";
}
else if(empty($area_1))
{
$sql = "SELECT * FROM deployment WHERE installation ='" . $installation_1 . "' AND district ='" . $district_1 . "'";
}
else if(empty($installation_1))
{
$sql = "SELECT * FROM deployment WHERE area ='" . $area_1 . "' AND district ='" . $district_1 . "'";
}
else
{
$sql = "SELECT * FROM deployment WHERE installation ='" . $installation_1 . "' AND area ='" . $area_1 . "' AND district ='" . $district_1 . "'";
}
$result = mysql_query($sql);
echo "<table id='table1' width = '500' align = 'center' style= 'border:1px'>";
echo "<tr><b>";
echo "<td>Installation</td>";
echo "<td>Area</td>";
echo "<td>District</td>";
echo "<td>Employee Name</td>";
echo "<td>Reference</td>";
echo "</b></tr>";
$employee = array();
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo ("<td>$row[installation]</td>");
echo ("<td>$row[area]</td>");
echo ("<td>$row[district]</td>");
echo ("<td>$row[employeename]</td>");
echo ("<td>$row[ref]</td>");
echo"</tr>";
$employee[] = $row['employeename'];
$arrlength = count($employee);
}
echo"</table>";
echo '<pre>'; print_r(array_filter($employee)); echo '</pre>';
?>
</body>
</html>
now I am getting error like this: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''M.A.JINNA,K.DHANA RAJU,B.EPHRIM'' at line 1
please give me any suggestions, thanks in advance
NOTE: I cannot use employee id instead of employee name due to client request
the code is
<?
$emp = implode( ',', $employee );
echo '<pre>'; print_r($emp); echo '</pre>';
$sql = "SELECT * FROM securitystaffdetails WHERE employeename IN '" . $emp . "'";
$result = mysql_query($sql) or die(mysql_error());
echo "<table id='table1' width='1500' style= 'border:1px'>";
echo "<tr><b>";
echo "<td>Employee Name</td>";
echo "<td>Address</td>";
echo "<td>DOB</td>";
echo "<td>Age</td>";
echo "<td>SEx</td>";
echo "<td>Mobile Number</td>";
echo "<td>Blood Group</td>";
echo "<td>ID Card</td>";
echo "<td>Ex Army Idcard</td>";
echo "<td>Police Clearence</td>";
echo "<td>ESI Card</td>";
echo "<td>PF Account</td>";
echo "<td>PAN Card</td>";
echo "<td>Voter ID</td>";
echo "<td>Ration/Family</td>";
echo "</b></tr>";
$employee = array();
while($record = mysql_fetch_object($result))
{
echo "<tr>";
echo ("<td>$record[employeename]</td>");
echo ("<td>$record[address]</td>");
echo ("<td>$record[dob]</td>");
echo ("<td>$record[age]</td>");
echo ("<td>$record[sex]</td>");
echo ("<td>$record[mobn]</td>");
echo ("<td>$record[bg]</td>");
echo ("<td>$record[icard]</td>");
echo ("<td>$record[exarmycard]</td>");
echo ("<td>$record[policeclearence]</td>");
echo ("<td>$record[esicard]</td>");
echo ("<td>$record[pfa]</td>");
echo ("<td>$record[pancard]</td>");
echo ("<td>$record[acard]</td>");
echo ("<td>$record[vcard]</td>");
echo ("<td>$record[rcard]</td>");
echo"</tr>";
}
echo"</table>";
?>
Change your implode line to be:
$emp = implode( "','", $employee );
and your query to be:
"SELECT * FROM securitystaffdetails WHERE employeename IN ('" . $emp . "')";
you missed ().
$sql = "SELECT * FROM securitystaffdetails WHERE employeename IN ('" . $emp . "')";

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.

Page authentication doesn't work

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.

Categories