php giving out blank pages (may be website setup) - php

Hi all I don't know if anyone will or can help me but for the last week or so I have been trying to make up a profile page setup on my website but I can not get the pages to register any echo's or jest even php (It gives me blank pages and or tell me an error 500 server error)
I have set up my website with a static page for my logo, navbar and footer and using a include line to get the content on the pages. (I hope that makes sense).
if I put any form of php into the content pages it give me errors of 500 server error and or the pages just turns completely white.
Is there a specific way to show SQL content and or any PHP with this set up? if anyone knows any tutorials or could lend a hand that would be amazing (Any help will be placed onto the website on the Credits page).
Here is the static page code:
<?php require '../connection/conn.php'; ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $title; ?></title>
<link rel="stylesheet" type="text/css" href="../css/Master.css" />
<link rel="stylesheet" type="text/css" href="../css/Menu.css" />
<link rel="stylesheet" type="text/css" href="../css/AboutImages.css" />
<link rel="stylesheet" type="text/css" href="../css/Form.css" />
</head>
<body>
<div class="container">
<div class="header">
<div id="logindata"></div>
</div>
<div class="menu">
<nav>
<ul class="cssmenu">
<li>Home</li>
<li>About Us</li>
<li>Videos</li>
<li>Contact Us</li>
<li>Forum</li>
<li></li>
<li>My Account</li>
<li>Logout</li>
</ul>
</nav>
</div>
<div class="content">
<?php echo $content;?>
</div>
<div class="footer">
<p>All Rights Reserved, LPGamers.com, Created And Built by Robert Prince & Amber Milton-White</p> Credits Page
</div>
</div>
</body>
</html>
And the content page:
<?php
$title = 'LPGamers -- Personal Account';
$content = '
<div id="formbox">
<form action="" method="GET">
<p>Search for you friends here !</p>
<input type="text" class="tfield">
<input type="submit" class="button">
</form>
</div>
<div class="ppicture">
<img src="" />
</div>
<div class="pd">
</br>
<p class="pdp">
Account id: # $userid
</p>
</br>
<p class="pdp">
Name:
</p>
</br>
<p class="pdp">
Age:
</p>
</br>
<p class="pdp">
Your Email:
</p>
</br>
<p class="pdp">
Your Bio:
</p>
</div>
';
include ("Site_View.php");
?>
If this help any more Thanks in advance

Edited the answer, it looks like some content of the original post was not displayed initially.
Do not put the form in the PHP code, it is not needed. You want to put the result probably there.
If you want to get data from SQL in PHP do the following:
Prerequisite: setup the php.ini to use whatever database you need, like:
extension=php_sqlsrv_56_nts.dll
Define a database connection
$serverName = "myserver";
$usr="mySQLuser";
$pwd="mySQLpass";
$db="mydatabase";
$connectionInfo = array("UID" => $usr, "PWD" => $pwd, "Database" => $db);
$conn = sqlsrv_connect($serverName, $connectionInfo);
if( !$conn ) {
die( print_r( sqlsrv_errors(), true));
}
Use the SQL connection to retrieve data.
$sql = "Select name from Users where users.name = " . $myparam;
note: the example above is vulnerable to SQL injection, but it is an easy start for coding, you can fix this later when you are familiar with it. Also you need to give a value to $myparam first.
Then:
$stmt = sqlsrv_query($conn, $sql);
sqlsrv_next_result($stmt);
sqlsrv_fetch($stmt);
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
Now you can use the data when you want, like this:
<?php
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$returnedName = $row['name'];
echo $returnedName;
}
?>

Related

Return to the place of POST

Please, if someone have idea how to do it...
I have created blog where are many post. Each of the post having 'like', 'not like' and 'comments' (as on the many websites of posts).
When I click on 'like'(is in html part inside of element form) of one of the post by the form element I submit POST. Then in php of the same file I increase value of 'like' in database. This value is by echo shown in the proper post updated from database.
The trouble is by doing this update I am not returning to place of increased 'like'. How to go back where I submit POST?
I have seen for example in Instagram when I click 'like' there is no move from the place, staying on the same one where click was made.
Thanks a lot for let me know...
<?php
$conn = mysqli_connect("localhost", "root", "", "amoscaguias_db");
if(!$conn) {
echo "<h3>No connection to database</h3>";
}
if(isset($_POST['increase-btn'])) {
$post_id = $_POST['post_id'];
$value = 0;
$stmt= $conn->prepare("SELECT very_like FROM blog_data WHERE id=? LIMIT 1");
$stmt->bind_param('i', $post_id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$result_1 = $row['very_like'];
$result_1 = $result_1 + 1;
$stmt1 = $conn->prepare("UPDATE blog_data SET very_like=$result_1 WHERE id=$post_id");
$stmt1->execute();
header("Location: index.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.8.1/font/bootstrap-icons.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>blog_php_mysql</title>
</head>
<body>
<div class="row">
<?php foreach($query as $q) { ?>
<div class="col-12 post">
<div class="card post-card mt-5">
<img class="card-img-top img-thumbnail post-card-image" src="imgs/<?php if(!empty($q['image'])) { echo $q['image']; } ?>" alt="<?php if(!empty($q['image'])) { echo $q['image']; } ?>">
<div class="card-body post-card-body">
<h5 class="card-title"><?php echo $q['title']; ?></h5>
<hr class="mx-auto">
<p class="card-text"><?php echo $q['content']; ?></p>
<hr class="mx-auto">
<div class="row ">
<div class="col-3 post-footer">
<form action="index.php" method="POST">
<button type="submit" id="increase" class="increase_btn" name="increase-btn"><i class="bi bi-hand-thumbs-up"></i></button>
<input type="hidden" name="post_id" value="<?php echo $q['id']; ?>" />
</form>
<span><?php echo $q['very_like'] ?></span>
<form action="index.php" method="POST">
<button type="submit" id="decrease" class="decrease_btn" name="decrease-btn"><i class="bi bi-hand-thumbs-down"></i></button>
<input type="hidden" name="post_id" value="<?php echo $q['id']; ?>" />
</form>
<span><?php echo $q['dont_like'] ?></span>
Comments
</div>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous">
</script>
<script src="js/myscript.js"></script>
</body>
</html>
There are several ways to do it:
Common and pretty way: Make an XHR request via javascript to the separate action (endpoint) on the backend, where you will extract data from the POST array, update the value in the database and return response in JSON format, which you can parse easily and set a new value. Also, sometimes there is the approach to increment likes via javascript before the backend will send an acknowledgment about the successful update - it's because likes are not so much important data.
Less common and a bit ugly way: you may add an anchor link on each post.
When you hit the 'like' button, you should send additional data, which includes the way to get this anchor link on the backend. After the backend successfully updates the value, you should redirect to the previous page with an anchor point to the liked post, so you will "return to the same place", because the browser will automatically scroll the page to the block with that anchor.

Unknown issue with $_SERVER["REQUEST_METHOD"] returning false when it should be true

Hey there stackoverflow users, i have come upon a very confusing problem that I cant seem to move past. I am creating a forum type web page and am currently working on the comments section. I have a form that uses the post method to send your comment as well as a hidden input to store the threads ID. I will post the entire php file below just to make sure nothing is left out.
<?php
session_start();
parse_str($_SERVER['QUERY_STRING'], $link);
$threadID = $link['ID'];
require("config.php");
$connection = mysqli_connect($host, $user, $password, $database);
$error = mysqli_connect_error();
if($error != null) {
$output = "<p>Unable to connect to database!</p>";
exit($output);
} else {
//Get Thread Data
$query = "SELECT username, title, content FROM threads, users WHERE threads.ID = $threadID AND users.ID = threads.makerID;";
$results = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($results);
//Get Comment Data
$query = "SELECT username, comment FROM comments, users WHERE threadID = $threadID AND users.ID = comments.makerID;";
$results = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($results);
}
?>
<!DOCTYPE html>
<html>
<head lang="en">
<title>BodyweightMate</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/styling.css"/>
</head>
<body>
<!--Top masthead-->
<header class="masthead" id="top">
<h1 class="masthead-title"> Welcome To BodyweightMate </h1>
</header>
<!--Navigation bar-->
<nav class="navbar">
<table class="navbar-table">
<tr>
<!--Logo-->
<td>
<a class="navbar-brand" href="main.php">
<img src="../images/logo.jpg" alt="BodyweightMate" height="30" width="30">
</a>
</td>
<!--Login/Profile-->
<?php if(isset($_SESSION['login_user'])) {
echo"<td><a class=\"navbar-profile\" href=\"profile.php\"> Profile </a></td>";
echo"<td><a class=\"navbar-logout\" href=\"logout.php\"> Logout </a></td>";
} else {
echo"<td><a class=\"navbar-login\" href=\"login.php\"> Login </a></td>";
}?>
</tr>
</table>
</nav>
<!--Main portion-->
<section class="content-section">
<article>
<h3><?php echo $row['username']. ": " .$row['title']; ?></h3>
<p><?php echo $row['content']; ?></p>
<br>
<h3>Comments</h3>
<p>Some annoying user: Gr8 B8 M8</p>
<p>Annoying users friend: I R8 8/8</p>
</article>
<div>
<!--If logged in, ability to comment-->
<?php if(isset($_SESSION['login_user'])): ?>
<form role="comment-form" method="POST" action="processcomment.php" id="mainForm">
<input type="hidden" value="$threadID" name="threadID">
<div class="form-group">
<label for="comment">Comment </label> <br>
<textarea class="comment-text" name="comment" rows="2" maxlength="255"></textarea>
</div> <br>
<input type="Submit" class="btn-newcomment" value="Submit Comment" name="submit">
</form>
<?php endif ?>
</div>
</section>
<!--Right portion-->
<aside class="content-aside">
<div>
<!--If logged in, be able to create a thread-->
<?php
if(isset($_SESSION['login_user'])) {
echo"<form method=\"post\" action=\"makethread.php\">";
echo"<input type=\"submit\" class=\"btn-newthread\" value=\"Create New Thread\" name=\"submit\">";
echo"</form>";
}
?>
</div>
<!--Info-->
<div>
<p> GOING TO NEED A SEARCH FUNCTION HERE
This is the cool little aside section. It will always be there to provide you with some very nice little details, helpful links, maybe a list of moderators? who knows! The uses are endless when you have a beautiful little aside like this one! Here are a few very useful bodyweight fitness links to get us started :D </p>
</div>
<br>
<div>
<ul class="content-aside-links">
<li>
Reddit's Bodyweightfitness Forum
</li>
<li>
Reddit's Bodyweightfitness RR
</li>
<li>
Antranik's Bodyweightfitness Routine
</li>
</ul>
</div>
<div></div>
</aside>
<!--Footer -->
<footer class="footer">
<div>
<p> Use of this site constitutes acceptance of our User Agreement © 2017 BodyweightMate inc. All rights reserved. </p>
</div>
</footer>
</body>
</html>
The error is occurring under the main portion where i check if a user is logged in, and if they are add a short form consisting of a message, a text area, and a submit button. This form sends the information to the following php file.
<?php
session_start();
if(!isset($_SESSION['login_user'])) { header("location: main.php"); }
?>
<!DOCTYPE html>
<html>
<body>
<?php
require("config.php");
$connection = mysqli_connect($host, $user, $password, $database);
$error = mysqli_connect_error();
if($error != null) {
$output = "<p>Unable to connect to database!</p>";
exit($output);
} else {
//Validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$comment = $_POST['comment'];
$threadID = $_POST['threadID'];
$user = $_SESSION['login_user'];
} else {
//Redirect back to register
echo"<p>Form must use post or input was bypassed.</p>";
echo" Return to home page. ";
mysqli_close($connection);
exit();
}
There is no issue with connecting to the database, and I don't believe the remainder of the code is necessary to help me with this error since that one if statement of checking if the form is using post is failing and the else statement is always called. Why is this? i have rewritten the form multiple times ensuring that its properly structured and using post yet it fails every time!

PHP issue with displaying a mySQLi result [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm having a rather confusing issue with a result that will not display. I'm creating a mailshot application and I'm trying to populate the email with the recipients name as well as an advert. The result works fine when I store it for use with the email that it sends to but it wont display inside the email body. Its a little hard to explain but here is the code that I am using. I have removed a lot of the email body as it was pretty large, where the ... are that is where I've take a load out.
<?php require (__DIR__.'/connections/connections.php');
session_start();
if(isset($_SESSION["UserID"])){
}else{
header('Location: login.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">
<head>
<title>AzTecks Staff | Search Results</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="css/coin-slider.css" />
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</head>
<body>
<div class="main">
<div class="header">
<div class="header_resize">
<div class="menu_nav">
<ul>
<li><span>Staff Home</span></li>
<li><span>Register Client</span></li>
<li class="active"><span>Register Applicant</span></li>
<li><span>Add Vacancy</span></li>
<li><span>Logout</span></li>
</ul>
</div>
<div class="logo">
<h1><span>AzTecks</span> <small style=" height: 12px; font-size: 11px;"> We Advise, We Avertise,</small><small style=" height: 12px; font-size: 11px;"> We Guarantee Not To Compromise</small></h1>
</div>
<div class="clr"></div>
<div class="slider">
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
</div>
<div class="content">
<div class="content_resize">
<div class="mainbar" style="margin-top:0px;">
<?php
echo "<div class=\"article\"><h2>Sending emails, please wait...</h2></div><br />";
/*Variables for mail shot query*/
$Keywords = $_SESSION['aKeywords'];
$Lname = $_SESSION['aLname'];
$Fname = $_SESSION['aFname'];
$CurrentJob = $_SESSION['aCurrentJob'];
$DesiredJob = $_SESSION['aDesiredJob'];
$CurrentSalary = $_SESSION['aCurrentSalary'];
$DesiredSalary = $_SESSION['aDesiredSalary'];
$Town = $_SESSION['aTown'];
$Country = $_SESSION['aCountry'];
$QualLevel = $_SESSION['aQualLevel'];
$Languages = $_SESSION['aLanguages'];
$TPC = $_SESSION['aTPC'];
$TechnicalTerms = $_SESSION['aTechnicalTerms'];
$ApplicantDivision = $_SESSION['aApplicantDivision'];
$query = "SELECT * FROM Applicants WHERE (? IS NULL OR CV_Text LIKE ?) AND (? IS NULL OR Applicant_Last_Name LIKE ?) AND (? IS NULL OR Applicant_First_Name LIKE ?) AND (? IS NULL OR Applicant_Current_Job_Title LIKE ?) AND (? IS NULL OR Applicant_Desired_Job_Title LIKE ?) AND (? IS NULL OR Applicant_Current_Salary >= ?) AND (? IS NULL OR Applicant_Desired_Salary >= ?) AND (? IS NULL OR Applicant_Town LIKE ?) AND (? IS NULL OR Applicant_Country LIKE ?) AND (? IS NULL OR Applicant_Qualification_Level LIKE ?) AND (? IS NULL OR Applicant_Languages LIKE ?) AND (? IS NULL OR T_P_C LIKE ?) AND (? IS NULL OR Applicant_Division LIKE ?) AND (? IS NULL OR Technical_Terms LIKE ?)";
$KeywordsW = '%'.$Keywords.'%';
$LnameW = '%'.$Lname.'%';
$FnameW = '%'.$Fname.'%';
$CurrentJobW = '%'.$CurrentJob.'%';
$DesiredJobW = '%'.$DesiredJob.'%';
$TownW = '%'.$Town.'%';
$CountryW = '%'.$Country.'%';
$QualLevelW = '%'.$QualLevel.'%';
$LanguagesW = '%'.$Languages.'%';
$TPCW = '%'.$TPC.'%';
$TechnicalTermsW = '%'.$TechnicalTerms.'%';
$ApplicantDivisionW = '%'.$ApplicantDivision.'%';
$stmt = $con->prepare($query);
$stmt->bind_param("ssssssssssiiiissssssssssssss", $Keywords, $KeywordsW, $Lname, $LnameW, $Fname, $FnameW, $CurrentJob, $CurrentJobW, $DesiredJob, $DesiredJobW, $CurrentSalary, $CurrentSalary, $DesiredSalary, $DesiredSalary, $Town, $TownW, $Country, $CountryW, $QualLevel, $QualLevelW, $Languages, $LanguagesW, $TPC, $TPCW, $ApplicantDivision, $ApplicantDivisionW, $TechnicalTerms, $TechnicalTermsW);
$stmt->execute() or die("Something went wrong, could not search :-(");
$result = $stmt->get_result();
$count = mysqli_num_rows($result);
if ($count == 0) {
$output = 'Sorry, no results found!';
echo $output;
}
else {
while($row = $result->fetch_object()) {
$id = $row->Applicant_ID;
$queryResult = $con->query("SELECT Contact_Email FROM Client_Contacts WHERE Contact_ID = {$_SESSION['coID']}");
$ContactDetails = $queryResult->fetch_object();
$email = $ContactDetails->Contact_Email;
$firstname = $row->Applicant_First_Name;
$lastname = $row->Applicant_Last_Name;
$mail_body = "<!doctype html>
<html>
...
Hello ".$ContactDetails->Contact_First_Name." ".$ContactDetails->Contact_Last_Name."<br /><br /><br />
Below is a potential applicant for your consideration.<br /><br />".$row->Applicant_Advert."<br /><br />
...</html>";
$subject = $_SESSION['eSubject'];
$headers = "From:natalie#aztecksonline.net\r\nContent-type: text/html\r\n";
$to = $email;
$mail_result = mail($to,$subject,$mail_body,$headers);
}
}
if($mail_result) {
echo "<script>window.alert(\"Mail Shot Sent!\");</script>";
header('location: index.php');
} else {
echo "Something went wrong :-(";
}
?>
</div>
<div class="sidebar">
<div class="searchform">
<form id="formsearch" name="formsearch" method="post" action="#">
<span>
<input name="editbox_search" class="editbox_search" id="editbox_search" maxlength="80" value="Search Applicants" type="text" />
</span>
<input name="button_search" src="images/search.gif" class="button_search" type="image" />
</form>
<br />
<div class="clr"><div id="google_translate_element"></div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script>
</div>
</div>
<div class="clr"></div>
<div class="gadget">
<h2 class="star"><span>Sidebar</span> Menu</h2>
<div class="clr"></div>
<ul class="sb_menu">
<li>Staff Home</li>
<li>Register Client</li>
<li>Register Applicant</li>
<li>Add Vacancy</li>
<li>Logout</li></ul>
</div>
<div class="gadget">
<h2 class="star"><span>Recent Vacancies</span></h2>
<div class="clr"></div>
<ul class="ex_menu">
<?php
if($cat_side_result = $con->query("SELECT Vacancy_ID, Vacancy_Job_Title, Vacancy_Location FROM Vacancies LIMIT 6")) {
if($cat_side_result->num_rows) {
while($cat_side_row = $cat_side_result->fetch_object()) {
echo '<li>'.$cat_side_row->Vacancy_Job_Title.'<br /> In '.$cat_side_row->Vacancy_Location.'</li>';
mysqli_close($con);
}
}
}
?>
</ul>
</div>
</div>
<div class="clr"></div>
</div>
</div>
<div class="fbg">
<div class="fbg_resize">
<div class="col c1">
<h2>Clients Recently Joined</h2>
<img src="images/Small_Company_logo_ABP.jpg" width="75" height="75" alt="" class="gal" /> <img src="images/Jumpahead1.jpg" width="75" height="75" alt="" class="gal" /> <img src="images/Keopple_logo_small.jpg" width="75" height="75" alt="" class="gal" /> <img src="images/Phantom_small.jpg" width="75" height="75" alt="" class="gal" /> <img src="images/graves-capital_small.jpg" width="75" height="75" alt="" class="gal" /> <img src="images/global-financial-logo_small.gif" width="75" height="75" alt="" class="gal" /> </div>
<div class="col c2">
<h2><span>Services</span> Overview</h2>
<p>At AzTecks we are committed to insuring you have total confidentiality, and do not share any data or information without your say so, please read our privacy agreement for more information.</p>
<ul class="fbg_ul">
<li>More about us</li>
<li>Privacy agreement</li>
<li>Contact us</li>
</ul>
</div>
<div class="col c3">
<h2><span>Contact</span> Us</h2>
<p>If you have any querys about us or have any questions please feel free to contact us.</p>
<p class="contact_info"> <span>Address:</span>1 Shaw Street<br />
Worcester , Worcestershire , UK<br />
<span>Postcode:</span> WR1 3QQ<br />
<span>Telephone:</span> 01905 700158<br />
<span>E-mail:</span>info#aztecksonline.net</p>
</div>
<div class="clr"></div>
</div>
</div>
<div class="footer">
<div class="footer_resize">
<p class="lf">© Copyright AzTecks.</p>
<div style="clear:both;"></div>
</div>
</div>
</div>
</body>
</html>
the $email populates fine as it sends the email with no issue but where it says in the email body $ContactDetails->Contact_First_Name, it does not display at all.
Have I done something rather dumb or is there something else wrong?
The query should look like this:
SELECT Contact_Email, Contact_First_Name, Contact_Last_Name FROM Client_Contacts WHERE Contact_ID = {$_SESSION['coID']}
You forgot to add Contact_First_Name and Contact_Last_Name into it so it wasn't even fetching them.
Start by adding at the top.
error_reporting(E_ALL);
ini_set('display_errors', '1');
And then add a die(); or exit(); before you actually execute any database updates and then check what is the error in the errors shown by php.
Normally this is because of an illegal way of executing the SQL in question. Try it out.
At first, you should write a readable code.
Now it's a really bad spaghetti code with crazy indentation (read about PSRs).
After that, separate your PHP from HTML, and move interaction with database to a different layer.

Multi-file Website and PDO: Undefined variable in method call (defined in another file)

EDIT: New Question (Previous answered, stupid mistake)
I corrected the below code to call $dbh into the menu function (nav.php). However, now I am getting a new error that Google isn't helping me with (all answers are program specific):
PDOStatement::execute(): SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected in /CCU/STH Liquidations/scripts/GetData.php on line 10
No database handle errors were thrown prior to trying to pull the menu in.
I am new to PDOs, so this might be a relatively simple question - but I couldn't find an answer close enough to my problem to help.
I am building my first true content management system. I am trying to bring in a menu based on whether it is to be shown (value is either 1 or 0, to be determined by admin).
However, in just trying to read them in, I'm getting undefined variable errors between files. The files are called in the correct order, and both are pulled in by index.php.
The variable that is undefined is the $dbh in the GetData.php file.
Do you see what I'm doing wrong? Because I can't see it.
index.php:
<?php
session_start();
$title = "STH Liquidations";
$description = "Product wholesale";
$keywords = "wholesale, product, pallets";
include "parts/_head.php";
include "parts/header.php";
include "parts/nav.php";
?>
<div id="content_index">
<?php include "parts/hot_deals.php"; ?>
<div id="image_holder">
<ul class="bxslider">
<li><img src="slider/pic1.jpg" title="Welcome to STH Liquidations!"/></li>
<li><img src="slider/pic2.jpg" title="Electronics"/></li>
<li><img src="slider/pic3.jpg" title="Furniture" /></li>
<li><img src="slider/pic4.jpg" title="Appliances" /></li>
<li><img src="slider/pic5.jpg" title="Tools" /></li>
<li><img src="slider/pic6.jpg" title="Sporting Goods"/></li>
</ul>
</div>
<p class="head1">Welcome to <strong>STH Liquidations, Inc.</strong></p>
<p>We at <strong>STH Liquidations, Inc.</strong> have been in the business of buying and selling overstock and liquidated NAME BRAND merchandise from <strong>major retailers</strong>, catalog companies, and big box stores for over 10 years now. Our goal has always been to consistently provide your business with <strong>dependable</strong> and <strong>trustworthy</strong> service along with the best possible pricing that will allow you to <strong>MAXIMIZE YOUR PROFITS</strong> and <strong>minimize your risk</strong> on every deal. Whether your business is wholesale, retail, auctions, online, flea markets, or if you are a “mom and pop store”, we are able to meet your specific needs.
</p>
<p>We carry truckloads of general merchandise, furniture, housewares, tools, toys, sporting goods, jewelry lots, apparel and much more. We ship direct from the reclaim centers, which eliminates “cherry picking” and keeps <strong>YOUR COST LOW</strong>. Our simple philosophy; <strong>money saved is money made</strong>. Your success is our success.</p>
<p>Please feel free to browse our website at your leisure and CALL us with ANY questions you may have to <strong>place your order</strong>.</p>
<p>Join our FREE mailing list HERE to receive <strong>up to date listings</strong> and our <strong>HOT deals</strong>.</p>
</div>
<div id="hotdeals">
<p class="head2">Hot Deals!</p>
<div class="deals">
<p class="deal_title">K-Hardgoods</p>
<p class="deal_desc">Truckloads, general merchandise, tools, toys housewares and more</p>
<p class="deal_price">as low as $139 per pallet</p>
<p class="deal_pdf">Call for Information!</p>
</div>
<div class="deals">
<p class="deal_title">SRS Tool Truckload</p>
<p class="deal_desc">CR*STSM*N TOOLS AND MUCH MORE <br />Saws, compressors, blowers, edgers. saber saws, table saws and much more</p>
<p class="deal_price">27 PALLETS--WHLS $66,649.32 <br />SELL PRICE $12,900</p>
<p class="deal_pdf">Download PDF</p>
</div>
<div class="deals">
<p class="deal_title">W*M Power wheels</p>
<p class="deal_desc">Ride on toy truckloads
<br />150-180 units per truckload
<br />Customer returns</p>
<p class="deal_price">Price only $5,900</p>
</div>
</div>
<div class="clear"></div>
<?php
include "parts/footer.php";
?>
_head.php:
<!DOCTYPE html>
<html>
<?php
require "config.php";
require_once "scripts/GetData.php";
?>
<head>
<!-- NAME THE PAGE -->
<title><?php $title ?></title>
<!-- GET THE FAIRY DUST AND DUST BUNNIES -->
<link rel="stylesheet" type="text/css" href="scripts/basic.css" />
<script type="text/javascript" src="contact-files/contact-form.js"></script>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<!-- bxSlider -->
<script src="scripts/jquery.bxslider.min.js"></script>
<link href="scripts/jquery.bxslider.css" rel="stylesheet" />
<script src="scripts/muscles.js"></script>
<!-- TELL GOOGLE WHAT IT WANTS TO HEAR -->
<meta name="description" content="<?php $description ?>">
<meta name="keywords" content="<?php $keywords ?>">
<!-- FIX ENCODING ERROR -->
<meta charset="UTF-8">
</head>
<!-- =============== -->
<!-- HEADER -->
<!-- =============== -->
config.php:
<?php
$host = "localhost";
$user = "root";
$pass = "root";
$database_name = "sthliquidations";
// Create connection
try
{
// PDO Connection
$dbh = new PDO("mysql:host = $host; dbname = $database_name", $user, $pass);
}
catch (PDOException $e)
{
echo $e -> getMessage();
}
// Show me any exceptions
// TURN THIS OFF WHEN LIVE
$dbh -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
?>
GetData.php (and where the error is being thrown):
<?php
function menu ($dbh)
{
// Make a call to the database
$menu_handle = $dbh->prepare("
SELECT * FROM cats
WHERE menu = ?;
");
$menu_handle->execute(array(1));
// Testing
$row = $menu_handle->fetch();
echo "<pre>";
echo $row;
echo "</pre>";
}
?>
nav.php (what's making the call in the first place):
<!-- NAVBAR -->
<div id = "sidenav">
<div id = "leftnav">
<ul class = "menulink">
<li>Home</li>
<li>About Us</li>
<?php menu($dbh); ?>
<li>Freight Services</li>
<li>Contact Us</li>
<li>Glossary</li>
</ul>
</div>
</div>
It was a simple fix after all. Scope was correct, call was correct - simply forgot the parameter.
Once I added the $dbh call in the correct places, I started getting this error:
PDOStatement::execute(): SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected in /CCU/STH Liquidations/scripts/GetData.php on line 10
After some trial and error, I figured out that the PDO database connection script doesn't like spaces.
Connected perfectly after that fix and have gotten my menu working properly, even able to pull in only those menu links set to true.
Days work done LOL!

Can't get login feature to work

I'm currently learning PHP and am creating a small CMS feature that includes a login area. I have used the code below which includes an include header file that contains the doctype/head info and the opening tag. It also includes the header content. I also have a connection file for connecting to the db.
My header include code is:
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title><?php echo $pagetitle ?></title>
<link rel="stylesheet" href="../stylesheets/foundation.css">
<link rel="stylesheet" href="../stylesheets/app.css">
<style>#import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800); #import url (http://fonts.googleapis.com/css?family=Kreon:100,200,300,400);</style>
<script src="../javascripts/modernizr.foundation.js"></script>
</head>
<body>
<div class="subHeader">
<div class="row">
<div class="four columns logo">
<img src="../images/logo.png" alt="logo" />
</div>
<div class="eight columns navigation right">
<ul class="navigationMain">
<li class="<?php if($navcurrent == "home"){echo "navigationActive";} ?>">Home</li>
<li class="<?php if($navcurrent == "services"){echo "navigationActive";} ?>">Services</li>
<li class="<?php if($navcurrent == "work"){echo "navigationActive";} ?>">Recent Work</li>
<li class="<?php if($navcurrent == "about"){echo "navigationActive";} ?>">About</li>
<li class="<?php if($navcurrent == "contact"){echo "navigationActive";} ?>">Contact</li>
</ul>
</div>
<div class="twelve columns titlesection">
<h2><?php echo $headTitle ?></h2>
<h4><?php echo $headsubTitle ?></h4>
</div>
</div><!--End Feature Row-->
</div><!--End Feature-->
<div class="underbar">
<div class="bordertriangle"></div>
<div class="row">
<div class="eight columns"> </div>
<div class="three columns right socialcontainer">
<ul class="socialicons">
<li><a><img id="linkedinIcon" src="../images/socialli.png" alt="linkedin icon" /></a></li>
<li><a><img id="twitterIcon" src="../images/socialtw.png" alt="twitter icon" /></a></li>
<li><a><img id="facebookIcon" src="../images/socialfb.png" alt="facebook icon" /></a></li>
</ul>
</div>
</div>
When I open the admin page, the username password form, header and footer appear as they should. If I test the errors, they return as they should. However, when I successfully log in using a valid username and password, no content appears except the what is included in the header file. Can anyone point me in the direction of what i might be doing wrong? Any help would be much appreciated. I am a relative noob to PHP...
<?php
$pagetitle = "Admin";
$navcurrent = "home";
$headTitle = "ADMIN AREA";
$headsubTitle = "SITE ADMINISTRATION AREA";
include_once('../includes/connection.php');
include_once('../includes/headeradmin.php');
if (isset($_SESSION['logged_in'])) {
echo('Successfully Logged In');
} else {
if (isset($_POST['username'], $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)){
$error = 'An Error Has Occurred - All Fields Are Required';
}
else{
$query = $pdo->prepare('SELECT * FROM users WHERE user_name = ? AND user_password = ?');
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('location: index.php');
exit();
}
else{
$error = 'The username/password you entered was incorrect - Please try again';
}
}
}
?>
<div class="row">
<div class="four columns centered">
<?php if (isset($error)) { ?>
<h5 style="color: #e63333;"><?php echo $error; ?></h5>
<br />
<br />
<?php } ?>
<form action="index.php" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>
</div>
</div>
You can't use the header('location: index.php'); line if you've already output content (i.e - html code) to the browser when you included the header in this line include_once('../includes/headeradmin.php');
read the documentation of header - Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP
you need to redirect the user with the header() function before you output the head html of the admin page

Categories