How use session variable in sql using php - php

I have a problem with displaying files added by the logged user.
I do not know how to pass the variable correctly to the sql query.
Can anyone help me with this?
Currently, the code looks like this:
<?php
include_once 'dbconnect.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>File Uploading With PHP and MySql</label>
</div>
<div id="body">
<table width="80%" border="1">
<tr>
<th colspan="4">your uploads...<label>upload new files...</label></th>
</tr>
<tr>
<td>File Name</td>
<td>File Type</td>
<td>File Size(KB)</td>
<td>View</td>
</tr>
<?php
$sql="SELECT * FROM files";
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set))
{
?>
<tr>
<td><?php echo $row['file'] ?></td>
<td><?php echo $row['type'] ?></td>
<td><?php echo $row['size'] ?></td>
<td>view file</td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
I am trying to change this record :
$sql="SELECT * FROM files";
to
$sql="SELECT file, type, size FROM files WHERE userId ='$_SESSION[userId]'";
but I still do not get the correct result. Can anyone help?

It looks like the issue with that line is in how you are including the $_SESSION variable. You should have quotes around userId like $_SESSION['userId'] or {$_SESSION['userId']}.
More importantly you should avoid entering variables directly into MySQL queries. I would recommend using MySQLi or PDO instead of MySQL, and look into prepared statements (here or here, for example).

Related

How to exclude HTML from PHP and PHP file still able to link with the HTML file?

View table<-- this is my example. And code is provided too. I need to separate HTML from PHP, moving HTML to another file but my PHP code still be able to link with it. Is there any idea? I am trying to make something like View model controller.
<html>
<head>
<meta charset="utf-8">
<title>View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>
Dashboard
| View Records
| Add Admin
| Logout
</p>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>ID</strong></th>
<th><strong>Username</strong></th>
<th><strong>User Password</strong></th>
<th><strong>Full Name</strong></th>
<th><strong>Edit</strong></th>
<th><strong>Delete</strong></th>
</tr>
</thead>
</body>
<?php
$count=1;
$sel_query="Select * from admin ORDER BY id ASC;";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td align="center"><?php echo $row["ID"]; ?></td>
<td align="center"><?php echo $row["username"]; ?></td>
<td align="center"><?php echo $row["user_pass"]; ?></td>
<td align="center"><?php echo $row["fullname"]; ?></td>
<td align="center">
Edit</td>
<td align="center">
Delete</td>
</tr>
<?php $count++; } ?>
</tbody>
</table>
</div>
</body>
</html>```
Separating the php and html is a good start, and helps you see the next step in converting to OOP and then MVC.
MVC at this point is too broad for a simple answer here, but I would recommend this as a first step as it has the underlying principles:
PHP is always at the top; never output anything until all your logic is finished
Load configuration
Work with user input and redirect if POST
Execute business logic
Exit PHP and output HTML. Remember, PHP is essentially a templating language, might as well use it as such
Your code would then look something like this:
<?php
// load database connection, etc
$url = 'your url';
// deal with user input. Always use POST if data will be changed!
if($_POST['action'] == 'delete') {
// delete from admin where id=?
header('location: '.$url);
die;
}
// end "controller" section
// begin "model" section
$sel_query="Select * from admin ORDER BY id ASC;";
$result = mysqli_query($con,$sel_query);
// end "model" section
// begin "view" section.
// Note, you could simply put the html in a separate file and just include it here.
?>
<html>
<head>
<meta charset="utf-8">
<title>View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>
Dashboard
| View Records
| Add Admin
| Logout
</p>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>ID</strong></th>
<th><strong>Username</strong></th>
<th><strong>User Password</strong></th>
<th><strong>Full Name</strong></th>
<th><strong>Edit</strong></th>
<th><strong>Delete</strong></th>
</tr>
</thead>
</tbody>
<?php while($row = mysqli_fetch_assoc($result)): ?>
<tr>
<td align="center"><?= $row["ID"] ?></td>
<td align="center"><?= $row["username"] ?></td>
<td align="center"><?= $row["user_pass"] ?></td>
<td align="center"><?= $row["fullname"] ?></td>
<td align="center">
<form method="post">
<input type="hidden" name="action" value="delete" />
<input type="hidden" name="id" value="<?= $row["ID"] ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</body>
</html>
Notice that following this pattern is laying the groundwork for moving to mvc. But first, start working on your oop chops and move all the business logic into a model object.
After that, you can move the template to its own file, and have the model injected into the view, which lets the view have access to the info it needs, and then render the output.
Meanwhile, you'll need a router (all traffic is rerouted to index.php) and controller, and figure out which interpretation of MVC you will use ;)
Here's a very basic solution.
Make an HTML file as a template. E.g. "template.html". Use HTML comments as placeholders for the data. (I went with comments as it means the HTML remains compliant)
I've left out some of the non-relevant bits, so hopefully you get the idea:
<html>
...
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>ID</strong></th>
<th><strong>Username</strong></th>
<th><strong>User Password</strong></th>
<th><strong>Full Name</strong></th>
<th><strong>Edit</strong></th>
<th><strong>Delete</strong></th>
</tr>
</thead>
<tbody>
<!--ROW-->
<tr>
<td align="center"><!--ID--></td>
<td align="center"><!--username--></td>
<td align="center"><!--user_pass--></td>
<td align="center"><!--fullname--></td>
<td align="center">
Edit</td>
<td align="center">
Delete</td>
</tr>
<!--ENDROW-->
</tbody>
</table>
</div>
</body>
</html>
Then, in your PHP code, you read in the html, find the row template, and replace the fields as needed:
<?php
// Read the template
$html = file_get_contents('template.html');
// Find the row template
$regRowTemplate = '/<!--ROW-->(.*)<!--ENDROW-->/i';
preg_match($regRowTemplate, $html, $m);
$rowTemplate = $m[1];
// Start building our replacement rows
$htmlRows = '';
$count=1;
$sel_query="Select * from admin ORDER BY id ASC;";
$result = mysqli_query($con,$sel_query);
while ($row = mysqli_fetch_assoc($result)) {
// Start with a fresh copy of the template
$htmlRow = $rowTemplate;
// Replace comment placeholders with values
foreach ($row as $key => $value) {
$htmlRow .= str_replace('<!--' . $key . '-->', $value, $htmlRow);
}
// Append to our rows
$htmlRows .= $htmlRow;
$count++;
}
// Replace the row template with our expanded rows
$html = preg_replace(regRowTemplate, $htmlRows, $html);
// Do something with the html
Source untested, but should give you a good starting point. I kept it pretty raw. If I was doing this for real, I'd allow for the possibility of spaces in the comment placeholders by using a regular expression instead, but for now it's good enough.

how do i display information from 3 tables into 1 table with php. i'm using mysql workbench

this is my code
<?php
$tilkobling = mysqli_connect("localhost","root","","oppgave_normalisering");
$sql = "SELECT person_table.personr, person_table.navn, person_table.adresse, person_table.mobilnr, person_table.postnr, person_table.bilde, mobil_table.model, sted_table.sted FROM mobil_table, person_table, sted_table";
$datasett = $tilkobling->query($sql)
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="test.css">
</head>
<body>
<table >
<tr>
<td style="text-align:center"><b>Nr<b></td>
<td style="text-align:center"><b>Navn<b></td>
<td style="text-align:center"><b>Adresse<b></td>
<td style="text-align:center"><b>Postnr</b></td>
<td style="text-align:center"><b>Sted</b></td>
<td style="text-align:center"><b>Mobilnr</b></td>
<td style="text-align:center"><b>Modell</b></td>
<td style="text-align:center"><b>Bilde</b></td>
</tr>
<?php while ($rad = mysqli_fetch_array($datasett)) { ?>
<tr>
<td style="text-align:center"><?php echo $rad["personr"]; ?></td>
<td style="text-align:center"><?php echo $rad["navn"]; ?></td>
<td style="text-align:center"><?php echo $rad["adresse"]; ?></td>
<td style="text-align:center"><?php echo $rad["postnr"]; ?></td>
<td style="text-align:center"><?php echo $rad["sted"]; ?></td>
<td style="text-align:center"><?php echo $rad["mobilnr"]; ?></td>
<td style="text-align:center"><?php echo $rad["model"]; ?></td>
<td style="text-align:center"><?php echo $rad["bilde"]; ?></td>
</tr>
</tr>
<?php } ?>
</table>
</body>
</html>
this is the result in google chrome.
This is what my tables look like in mysql workbench
as you can see under the Nr colum the numbers replicate themselves. i want it to only show 1, 2, 3 and not the replicated colums.
If you have a specific value that you`re looking for, you should be using WHERE, otherwise you can use SELECT DISTINCT at the beginning of your statement
Thanks for all the help!
The problem was solved with using "WHERE" + "AND". As you can see in the code i wrote
WHERE person_table.personr = sted_table.stednr AND person_table.personr = mobil_table.modelnr"
which were the colums that were interfering with eachother. This
solved the problem where the information was duplicating for each value in the Mobil_table.
End php code <
$sql = "SELECT person_table.personr, person_table.navn, person_table.adresse, person_table.mobilnr, person_table.postnr, person_table.bilde, mobil_table.model, sted_table.sted FROM mobil_table, person_table, sted_table WHERE person_table.personr = sted_table.stednr AND person_table.personr = mobil_table.modelnr";

How to debug a MySQL error in PHP?

I have code that normally don't have any problem with but somehow the MySQL query part (marked with an arrow ------>) is stopping the code.
The MySQL command is fine and the mysql_connection is working, I can ping it.
I'm working all the time like that, I just can't find the error, and since the code is completely stopping I can't fetch any error message.
<?php
//including the mysql_connection
include("../mechanics/mysql_con.php");
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../mechanics/segments_container.css"/>
</head>
<body>
<div class = "container">
<div class = "titlebar">
Members
</div>
<div class = "inner_container">
<center>
<table style="color:#CCCCCD;width:100%;">
<tr>
<td style="min-width:50px;text-align:center;"><b>Avatar</b></td>
<td style="min-width:150px;text-align:center;"><b>Username</b></td>
<td style="min-width:50px;text-align:center;"><b>Joined</b></td>
<td style="min-width:50px;text-align:center;"><b>Posts</b></td>
<td style="min-width:50px;text-align:center;"><b>Reputation</b></td>
</tr>
<?php
$mysql_get_users = "SELECT avatar, name, registerdate, posts, reputation FROM members";
-----> $data = $mysqli->query($mysql_get_users);
-----> while($row = $data->fetch_array()){
?>
<tr>
<td><?php echo $row["avatar"]; ?></td>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["registerdate"]; ?></td>
<td><?php echo $row["posts"]; ?></td>
<td><?php echo $row["reputation"]; ?></td>
</tr>
<?php
}
?>
</table>
</center>
</div>
</div>
</body>
</html>
I think I found the answer.
Because the file memberlist.php itself is a include from the index.php, the directory wasn't ../mechanics/mysql_con.php instead it was mechanics/mysql_con.php
I guess because of the including the path started from index and not the it's folder segments (where memberlist.php is in)
Thanks for every second. :)

Integrating PHP files into HTML files

I'm new in this language. I'm working on a website. I use HTML file like this:
<html lang="en">
...
<div class="" id="temperatura" name="temp">
<?php require 'php/staticsTemp.php'; ?>
<h3 class="centered">Temperature</h3>
<hr>
<br>
<table class="tg" border="5">
<tr>
<th class="tg-031e">Temperature ºC</th>
<th class="tg-031e">Date & Time</th>
</tr>
<tr>
<td class="tg-031e">33</td>
<td class="tg-031e">44</td>
</tr>
</table>
</div>
...
</html>
And I want to substitute the value 33 and 44 in the table to values that are inside the PHP file.
My PHP looks like this:
<?php
include("ligacaobd.php");
$sql="SELECT * FROM Valores ORDER BY Momento DESC LIMIT 20";
$result = mysql_query($sql, $ligacaobd) or die(mysql_error());
$rowValor = mysql_fetch_assoc($result);
do
{
$data[date('d/m/Y H:i:s', $rowValor['Momento'])]=$rowValor['Temperatura'];
}
while ($rowValor= mysql_fetch_assoc($result));
?>
Any thoughts? I tried with function POST, but in HTML doesn't work.
You must convert your html in .php as it is and include this php code, either directly in the page or via another php page.
You will then be able to manipulate your variables and do something such as:
<td class="tg-031e"><?php echo $myVariable1; ?></td>
<td class="tg-031e"><?php echo $myVariable2; ?></td>
I'm not quite certain what you mean, but I will try to help you.
First of all don't* use mysql functions anymore. These functions are no longer maintained. Use **mysqli or PDO instead.
If you want to show variables in a HTML document you can do the following thing.
<tr>
<td class="tg-031e"><?php echo $var1; ?></td>
<td class="tg-031e"><?php echo $var2; ?></td>
</tr>
Also I would recommend you separating your HTML files from the PHP or at least place your PHP code at the top of your document. For example:
<?php
$var1 = 'Example Variable';
?>
<html lang="en">
<head>
<title>Example</title>
</head>
<body>
<?php echo $var1; ?>
</body>
<html>
Yet the best practice is separating HTML from PHP.
Since you are new to the PHP language, I have some great tutorials for you.
Take a look at http://www.w3schools.com. They have some basic PHP tutorials for you to start with.
Good luck.
Don't use mysql_* functions anymore! They are deprecated in PHP 5.5 and should be removed in 5.6. Use PDO instead.
Not tested yet, but should work. You just need to change your <table /> code to this:
<table class="tg" border="5">
<tr>
<th class="tg-031e">Temperature ºC</th>
<th class="tg-031e">Date & Time</th>
</tr>
<?php foreach ($data as $datetime => $temperature): ?>
<tr>
<td class="tg-031e"><?php echo $temperature; ?></td>
<td class="tg-031e"><?php echo $datetime; ?></td>
</tr>
<?php endforeach; ?>
</table>
Hope it helps :)

Echo HTML with PHP in the middle

I am new to PHP and am running into a small problem with this code. I am trying to make a layout for a page that uses more PHP to fill in the blanks.
When I view the source <? include $navbar ?> is commented out but <?=$pagetitle?> works, why is that?
For reference:
$navbar = "navbar.php";
and navbar.php:
<?php echo "Select Car Change Profile"; ?>
Layout.php:
<?php
echo "
<html>
<head>
<title>Race Data. <?=$pagetitle?></title>
</head>
<body>
<div id='page'>
<table border='1'>
<tbody>
<tr>
<td colspan='3'>Banner goes here.<?=$pagetitle?></td>
</tr>
<tr>
<td rowspan='2'>Left menu</td>
<td colspan='2'><? include $navbar; ?></td>
</tr>
<tr>
<td>Content</td>
<td>Right menu</td>
</tr>
<tr>
<td colspan='3'>Footer</td>
</tr>
</tbody>
</table>
</div>
</html>
";
?>
I'm sure knowing this will help amny future problems I run into.
Also, what are the diferences in using <? ?> vs <?php ?>?
In php, you always need to use <?php /*code*/ ?>
The shorthand version to echo something is <?= /*string*/ ?>, but to run code, such as an include you would need to start with <?php. In your example, this would be:
<tr>
<td rowspan='2'>Left menu</td>
<td colspan='2'><?php include $navbar; ?></td>
</tr>
Correction
I only just noticed that you placed the PHP tags inside another set of PHP tags. You're kind of doing it the hard way. In a PHP file, anything is regarded as an echo, except for content inside <?php ?> tags. So this should work perfectly for you:
<html>
<head>
<title>Race Data. <?=$pagetitle?></title>
</head>
<body>
<div id='page'>
<table border='1'>
<tbody>
<tr>
<td colspan='3'>Banner goes here.<?=$pagetitle?></td>
</tr>
<tr>
<td rowspan='2'>Left menu</td>
<td colspan='2'><?php include $navbar; ?></td>
</tr>
<tr>
<td>Content</td>
<td>Right menu</td>
</tr>
<tr>
<td colspan='3'>Footer</td>
</tr>
</tbody>
</table>
</div>
</html>
The difference is that I didn't put <?php ?> tags around the whole thing.
Try
short_open_tag=On;
in php.ini
And restart your Apache server.

Categories