I'm new to php and backend, I tried making a login and I wanted to buttons to change the background colour. Instead of using javascript, I use php to program it, to create sessions.
Below is the code. The buttons work in the url bar, but nothing is happening.
What am I missing or overseeing?
<?php
// Initialize the session
session_start();
require_once "config.php";
session_start();
require_once "config.php";
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$sql = "SELECT background FROM users ORDER BY id DESC";
$backgroundColour = [];
$colour = [];
$result = $link->query($sql);
$data = [];
while ($row = $result -> fetch_object()) {
$data[] = $row;
}
$backgroundColour['backgroundColour'] = $data;
$_SESSION['colour'] = $colour;
if(isset($_GET['colour'])){
$colour = $_GET['colour'];
$_SESSION['colour'] = $colour;
}
$colour_session = $_SESSION['colour'];
$sql = "INSERT INTO users (background) VALUES ('$colour_session')";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<h1>Choose background color</h1>
Hvid
Sort
</div>
<title>Welcome</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<h1 class="my-5">Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
<p>
Reset Your Password
Sign Out of Your Account
</p>
</body>
</html>
At least you need to tell the client side (the browser) that the background color is set as $_SESSION["color"] (e.g. black)
So, one of the ways is to add the following line to the end of your script (your script already has <body></body>) :
<?php
echo '<script>document.body.style.backgroundColor = "'. $_SESSION['colour'] . '";</script>';
?>
So, omitting the db part, the code (tested, fully working) will be
<?php
session_start();
if(isset($_GET['colour'])){
$colour = $_GET['colour'];
$_SESSION['colour'] = $colour;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<h1>Choose background color</h1>
Hvid
Sort
</div>
</body>
<?php
echo '<script>document.body.style.backgroundColor = "'. $_SESSION['colour'] . '";</script>';
?>
For the db part:
You may need to re-write the part on the db queries. For example, apart from the need to use parameterized prepared statement in your query (to avoid SQL injection attacks). Consider using "update user set background=? where id=?" instead of an insert query, For a multi-user system, it will be something like:
$sql = "UPDATE users SET background=? WHERE id=?";
$stmt= $link->prepare($sql);
$stmt->bind_param("si", $_SESSION['colour'], $_SESSION["id"]);
$stmt->execute();
It is because each user should have only a single record in the db table (so logically it is an update instead of an insert).
Related
I want to make a page where the element will redirect the user to a random page from the database.
I made the HTML code, but I can not deal with PHP and MySQL - I was able to connect to the database, but any attempt to connect the MySQL code with the tag ended in a loss.
Can I count on help writing a PHP script and linking code with ?
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Montserrat+Subrayada" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet">
<title>Random it</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<header></header>
<div class="random">
Random
</div>
<?php
require_once "connect.php";
$conn = #new mysqli($host, $db_user, $db_password, $db_name);
$sql = "SELECT link FROM randomit ORDER BY RAND()";
?>
<footer></footer>
</body>
</html>
Let's try this:
Put this PHP part at the top of the page;
<?php
// set a default link in case something goes wrong
$DEFAULT_LINK = "default.html";
// connect to DB
require_once "connect.php";
$conn = new mysqli($host, $db_user, $db_password, $db_name);
// set query -> get 1 result only with LIMIT 1
$sql = "SELECT link FROM randomit ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn, $sql);
if ($result !== false)
$row = mysqli_fetch_assoc($result);
else
$row = false;
// if we have a valid result => use it
// else => use the default
if ($row && isset($row["link"]))
$RANDOM_LINK = $row["link"];
else
$RANDOM_LINK = $DEFAULT_LINK;
?>
And now the HTML part:
<!DOCTYPE html>
<html>
<!-- head part... -->
<body>
<header></header>
<div class="random">
Random
</div>
<footer></footer>
<!-- etc... -->
i am trying to buid a Php site that show data from my MySQl database.
and i think im almost there, everything works except the Pictures.
i cant get my php site to show the pictures with the picture reference from Sql database.
<!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">
<?php
$con=mysqli_connect("localhost","root","","db1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<head>
<link rel="stylesheet" href="styles.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>untitled</title>
</head>
<body>
<div class="content">
<?php
$sql = "SELECT id, Producent, Model, kategori FROM tb1";
$result = mysqli_query($con,"SELECT * FROM `tb1");
echo "<table>";
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>";?> <img scr="<?php echo $row["Billedurl"]; ?>"/> <?php echo " </td>";
echo "<td>" .$row["Producent"] .$row["Model"]; echo "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<!-- end .content --></div>
<!-- end .container --></div>
<div class="footer"><br>
<!-- end .footer --></div>
</body>
</html>
You need to select all the columns you are going to use, so if you need Billedurl, you should change:
$sql = "SELECT id, Producent, Model, kategori FROM tb1";
to:
$sql = "SELECT id, Producent, Model, kategori, Billedurl FROM tb1";
Now the value of that column will be available in $row["Billedurl"].
Edit: It seems that now you have the correct value in your html, but the path to the image is not correct as it is a relative path.
You should prefix your variable with the correct folder so that the image is found by the browser. That can be as simple as just using an absolute path but that depends on where the pic/ directory is located.
So if your variable contains pic/l_jabra_evolve80.jpg" and the pic/ folder is on the root of the web-server, you can do something like:
# before the loop
$imagePrefix = '/';
# in the loop
... <img scr="<?php echo $imagePrefix . $row["Billedurl"]; ?>"/> ...
Now the browser will try to fetch the image from /pic/l_jabra_evolve80.jpg.
You need to do little bit of debugging:
first change little bit in your query
$sql = "select * FROM tb1";
$result = mysqli_query($con, $sql);
Then try to check print_r($result) and check if you are getting everything here or not.
My knowledge of php is very limited, although I am aware that mysql functions are depreciated but it doesn't matter for the purpose of this project.
I have a table (enisatquestion) with training questions, and file paths to 14 videos stored on my pc which I want to display using localhost.
My table structure and an example of one of the rows in my table are as follows:
Columns are:
eNISATID (Auto-increment)
eNISATQuestion (Training question)
eNISATVideo (File path to video)
An example of a Row:
1
Can you login?
http://localhost\Tna\eNISAT\LoginTutorial.wmv
Here is my code, I am getting an error;
mysql_fetch_assoc() expects at least 1 parameter, 0 given in C:\wamp\www\Tna\eNISATVids.php on line 20
Can anyone please help me with this, I have researched a lot of ways to display this, but I am struggling with it as I have never worked with videos in php before. The videos are also wmv format. Or can anyone give me a more suitable example
Many Thanks
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
//maintain SESSION user_id
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
//Select video name and question
$query = "SELECT eNISATQuestion, eNISATVideo FROM enisatquestion";
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$enisatquestion = "<table >";
while ( $row = mysql_fetch_assoc($result) ) {
$enisatquestion .= "<tr><td><a href='{$row['eNISATVideo']}'>{$row['eNISATQuestion']}</a></td></tr>";
}
$enisatquestion .= "</table>";
echo $enisatquestion;
?>
<!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" />
<title>Welcome - <?php echo $userRow['username']; ?></title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<div id="left">
<label>NHSCT eNISAT Tutorials</label>
</div>
<div id="right">
<div id="content">
Welcome <?php echo $userRow['forename']; ?> Sign Out
</div>
</div>
</div>
</body>
</html>
The answer is simple:
$query = "SELECT eNISATName, eNISATVideo FROM enisatquestion";
$result = mysql_query($query);
$enisatquestion = "<table>";
while ( $r = mysql_fetch_assoc($result) ) {
$enisatquestion .= "<tr><td><a href='{$r['eNISATVideo']}'>{$r['eNISATName']}</a></td></tr>";
}
$enisatquestion .= "</table>";
echo $enisatquestion;
?>
Notice the new $result variable that is passed to mysql_fetch_assoc.
I working on a simple project, and basically what I am doing is that I am creating a simple page from admin panel and then displays it in another page using iframe...
So in the process of displaying the page names, I managed to display all the page names that I have in the database. However, when I try to give them a link so when the user click on them, it redirects them to the specific page. So if there is a page named: new york and he clicks on it, it goes to: /pages/newYork.php ...
The problem: When I give them a link, only 1 page link is given for all the pages. Example: If I had cities named: New York, Bangkok and Amsterdam, the link for all of those pages is only for New york.
Here is my code:
<?php
require_once '../connect.php';
session_start();
if(isset($_SESSION['loggedinAdmin'])){
}else{
header("Location: index.php");
}
// To display content:
$realDisplay = '';
$sql = mysql_query("SELECT * FROM cities");
while($row = mysql_fetch_assoc($sql)){
$displayName = $row['name'];
$realDisplay .= $displayName.'<br/>';
}
echo "<u align='center'>Page names:";
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Display Pages</title>
<style>
a{
text-decoration:none;
font-size:30px;
color:skyblue;
}
</style>
</head>
<body>
<div style="color:red;">
<a href="<?php echo 'pages/'.$displayName.'.php'?>">
<?php echo $realDisplay;?>
</a>
</div>
</body>
</html>
Any thoughts of how to solve this? Also, if there is a better way to do it then it would be great.
Thanks in advance for everybody :)
First, move your loop to the page where you are actually going to display the data.
Second, keep your code clean and readable by putting things where they actually belong. ie. <u align='center'>Page names: doesn't belong where you put it. It goes in the body.
Third, don't forget to properly close your tags. <u align='center'>Page names: has no closing tag.
Finally, don't over-complicate it. You don't need two different vars for the same data row.
<?php
require_once '../connect.php';
session_start();
if(isset($_SESSION['loggedinAdmin'])){
}else{
header("Location: index.php");
}
// To display content:
//$realDisplay = '';
$sql = mysql_query("SELECT * FROM cities");
//while($row = mysql_fetch_assoc($sql)){
//$displayName = $row['name'];
//$realDisplay .= $displayName.'<br/>';
//}
//echo "<u align='center'>Page names:";
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Display Pages</title>
<style>
a{
text-decoration:none;
font-size:30px;
color:skyblue;
}
</style>
</head>
<body>
<div align="center"><u>Page names:</u></div>
<div style="color:red;">
<?php while($row = mysql_fetch_assoc($sql)){
$displayName =$row['name']
?>
<?php echo $displayName;?><br>
<?php } ?>
</div>
</body>
</html>
I am trying to get my PHP to populate my page elements but the page will not output the results based on anything I trying in the where clause of my SQL (even though it works on my server. I don't know why nothing happens when this page is run with a where parameter (the posted variable is being captured). Let me know if you need more information.
<?php
//start output buffering
ob_start('ob_gzhandler');
session_name('shipshapeLogin');
session_set_cookie_params(2*7*24*60*60);
session_start();
define('INCLUDE_CHECK',true);
require('connect.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Organization Profile</title>
<link rel="stylesheet" type="text/css" href="profile.css" media="screen" />
</head>
<body>
<?php
$businessName = $_POST['companies'];
echo $businessName;
//check if username or email is already registered
$query = "SELECT * FROM Businesses_profiles WHERE business_name = :businessName";
//now lets update what :user should be
$query_params = array(
':businessName' => $businessName,
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
}
//fetching all the rows from the query
$profileRow = $stmt->fetch();
while ($profileRow = $stmt->fetch())
{
?>
<h1>Name</h1>
<p><?php echo $profileRow['business_name'];?></p>
<h1>Description</h1>
<p><?php echo $profileRow['description'];?></p>
<h1>Address</h1>
<p><?php echo $profileRow['address'];?></p>
<h1>Phone</h1>
<p><?php echo $profileRow['contact_phone'];?></p>
<h1>Email</h1>
<p><?php echo $profileRow['contact_email'];?></p>
<?php
}
?>
</body>
</html>
<?php
//end output buffering
ob_end_flush();
?>
I had to remove the $profileRow above the while loop.
/fetching all the rows from the query
$profileRow = $stmt->fetch();**
while ($profileRow = $stmt->fetch())
{
?>