I'm a noob to PHP/mySQL and I'm enjoying it, but I'm stuck... I'm in the process of developing my first database driven website. I've created the database, the tables... loaded one table in particular with content in an attempt to pull data from it via PHP. If you go to my website live via the browser, there is a navigation system that seems to work but, it's not loading content from the db table. It's just blank content with a nav system that changes the page in the address bar but blank content. I've provided the code along with a image shot of the table in my database I'm trying to GET the data from. The db table i'm getting from is called vls_pages. It is also the table featured in the image. I'm hoping someone can point me to getting this to function correctly. Thank you everyone
index.php CODE:
<?php
// Load Setup document:
include
('_config/setup.php'); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $page_title; ?></title>
<link rel="stylesheet" type="text/css" href="_css/styles.css">
</head>
<body>
<div class="wrap_overall">
<div class="nav_main">
<?php include('_template/nav_main.php'); ?>
</div>
<div class="body_header">
<?php get_page_name($dbc, $pg); ?>
</div>
<div class="content">
<?php get_page_body($dbc, $pg); ?>
</div>
<div class="footer">
<?php include('_template/footer.php'); ?>
</div>
</div>
</body>
</html>
setup.php CODE:
<?php
## Setup Document
// host(or location of the database), username, password, database name
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "***************";
$username = "***************";
$password = "***************";
//Connecting to your database
$dbc = #mysqli_connect($hostname, $username, $password) OR DIE ("Unsuccessful.");
// Check connection
if (mysqli_connect_errno($dbc))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
include('_functions/snippets.php');
if ($_GET['pgname'] == '') {
$pg = 'home';
}
else {
$pg = $_GET['pgname'];
}
$page_title = get_page_title($dbc, $pg);
?>
snippets.php CODE:
<?php
// Snippets; Functions
function get_page_title ($dbc, $pg) {
$query = "SELECT pgtitle FROM vls_pages AND pgstatus = 1 LIMIT 1";
$result = #mysqli_query($dbc, $query);
$page = #mysqli_fetch_assoc($result);
return $page['pgtitle'];
#mysqli_close($dbc);
}
function get_page_name ($dbc, $pg) {
$query = "SELECT pgname FROM vls_pages WHERE pgname = '$pg' AND pgstatus = 1 LIMIT 1";
$result = #mysqli_query($dbc, $query);
$page = #mysqli_fetch_assoc($result);
echo '<h1>'.$page['pgname'].'</h1>';
#mysqli_close($dbc);
}
function get_page_body ($dbc, $pg) {
// the database connection, our query
$query = "SELECT * FROM vls_pages WHERE pgbody = '$pg' AND pgstatus = 1 LIMIT 1";
$result = #mysqli_query($dbc, $query);
$page = #mysqli_fetch_assoc($result);
echo '<div class="content">'.$page['pgbody'].'</div>';
#mysqli_close($dbc);
}
?>
You're closing the database connection at the end of each function. So after you get the page title, the database connection closes.
Remove this line from the end of every function in setup.php:
#mysqli_close($dbc);
Then add that line to the end of index.php to close the connection after the page is done processing:
<?php
mysqli_close($dbc);
?>
This will solve the major issue described in the question. For the sake of completeness, you should also follow the recommendations in the comments area of the question. Specifically, the SQL query in get_page_title() should have "WHERE" instead of "AND", and remove the "#" error suppression, especially while you're learning.
there is a mistake in your query, you forgot to keep where condition please replace the following code
$query = "SELECT pgtitle FROM vls_pages AND pgstatus = 1 LIMIT 1";
with
$query = "SELECT pgtitle FROM vls_pages where pgstatus = 1 LIMIT 1";
As per the SELECT syntax in the manual on the MySQL.com website.
The syntax is SELECT select_expr FROM table_references WHERE where_condition equals
Now, this line is using the AND clause:
SELECT pgtitle FROM vls_pages AND pgstatus = 1 LIMIT 1
which should be using the WHERE clause, such as:
SELECT pgtitle FROM vls_pages WHERE pgstatus = 1 LIMIT 1
Consult lwitzel's answer also
Food for thought:
Do take the comments into (serious) consideration when it comes to properly sanitizing your inputs.
The use of PDO is highly recommended - PDO Tutorial
Related
I want to update/edit my user form, but when I click the "edit" button, I'm not getting the expected results. It should display the new data, but It displays the old data instead.
coding:
<?php
include"errorReporting.php";
include "conn.php";
$conn = connect();
$conndb = connectdb();
$wardID = $_REQUEST["wardID"];
$RequestName = $_REQUEST["RequestName"];
$Department = $_REQUEST["Department"];
$Position = $_REQUEST["Position"];
$Date= $_REQUEST["Date"];
$TypeOfRequest = $_REQUEST["TypeOfRequest"];
$PleaseSpecify = $_REQUEST["PleaseSpecify"];
$DateRequire = $_REQUEST["DateRequire"];
$DateReturn = $_REQUEST["DateReturn"];
mysqli_select_db($conn,"misadmin") or die ($conn->error ."\n");
$query = "select * from requestform";
$result2= $conn->query($query) or die ($conn->error ."\n");
$row_result =mysqli_fetch_assoc($result2);
mysqli_select_db($conn,"misadmin") or die ($conn->error ."\n");
$conn ->query("UPDATE requestform SET RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID='$wardID'",$conn->affected_rows);
$result_update=mysqli_fetch_assoc($result);
header("Location:requestform3.php");
?>
output:
try it:
$conn ->query("UPDATE requestform SET RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID=$wardID ");
in where wardID='???' Must retrieve the data before it changes. i mean "4f" not "med".
you can add a textbok in your post form :
<input type="hidden" id="original_wardID" value="<?php echo $wardID?>" />
in your php code add :
$ori_wardID=$_REQUEST['original_wardID'];
then change your sql :
UPDATE requestform SET wardID='$wardID',RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID='$ori_wardID'
"UPDATE requestform SET RequestName='$RequestName',Department='$Department',Position='$Position',Date='$Date',TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify',DateRequire='$DateRequire',DateReturn='$DateReturn' where wardID='$wardID'"
change to
"UPDATE requestform SET RequestName='".$RequestName."',Department='".$Department."',Position='".$Position."',Date='".$Date."',TypeOfRequest='".$TypeOfRequest."',PleaseSpecify='".$PleaseSpecify."',DateRequire='".$DateRequire."',DateReturn='".$DateReturn."' where wardID=".$wardID
or like this demo code
$db_sql="select id ,uid,regdate from `newtable` where id=?";
$stmt=$mysqli->prepare($db_sql);//
$stmt->bind_param("i",$id);// i int d double s string b blob
$result = $stmt->execute();
but I guess use pdo will be better
You are not using if ($_SERVER['REQUEST_METHOD'] == 'POST'){//save database} or if (isset $_POST['edit']){//save database} for the edit button in order to save data when edit button is clicked.
Plus you are using Date in your UPDATE query (Date =). DATE is also as a native function used in MYSQL, you need to change it. In case you changed it to DateChanged use prepared statement it helps your code to be more readable.
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
$stmt = $conn->prepare("UPDATE requestform SET RequestName=?,
Department=?, Position=?, DateChanged=?, TypeOfRequest=?,
PleaseSpecify=?, DateRequire=?, DateReturn=? WHERE wardID=?");
$stmt->bind_param("sssssssss", $RequestName, $Department,
$Position, $DateChanged, $TypeOfRequest, $PleaseSpecify,
$DateRequire, $wardID);
$stmt->execute();
$stmt->close();
$conn->close();
}
i had found my answer. after i redo back my coding using the old template
here are the code.
<?php
// to connect with the database system
include "errorReporting.php";
include "conn.php";
$conn = connect();
$conndb = connectdb();
$wardID = $_REQUEST["wardID"];
$RequestName = $_REQUEST["RequestName"];
$Department = $_REQUEST["Department"];
$Position = $_REQUEST["Position"];
$DateRequest = $_REQUEST["DateRequest"];
$TypeOfRequest = $_REQUEST["TypeOfRequest"];
$PleaseSpecify = $_REQUEST["PleaseSpecify"];
$DateRequire = $_REQUEST["DateRequire"];
$DateReturn = $_REQUEST["DateReturn"];
mysqli_select_db($conn,"misadmin") or die (mysql_error()."\n");
$query = "select * from requestform" ;
$result = $conn->query($query) or die (mysql_error()."\n".$query);
$row_result=mysqli_fetch_assoc($result);
mysqli_select_db($conn,"misadmin")or die (mysql_error(). "\n");
//to update the data
$update="update requestform SET
RequestName='$RequestName' ,Department='$Department' ,Position='$Position' ,DateRequest='$DateRequest' ,TypeOfRequest='$TypeOfRequest',PleaseSpecify='$PleaseSpecify' ,DateRequire='$DateRequire' ,DateReturn='$DateReturn' where wardID='$wardID'";
$rowinsert=$conn->query($update);
header("Location:requestform3.php");
?>
thanks for those who gave the suggestions.I had learnt a lot from you all.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm very new to PHP/Mysql and I naturally have a few questions. I was following a youtube tutorial on creating a simple dynamic website that pulls data content from a MySQL database then displays the content on a single PHP index page. I followed this tutorial to the point where I was using PHP/MySQL to connect to the DB, run a query, fetch the query using a fetch_assoc array. but nothing would display in the body of the page. During the trouble shooting process I was advised that I should be using PDO instead of the older MySQL methods. Can someone decipher my current "older" MySQL code and translate it into the proper PDO coding approach so that I can learn to grasp PDO, since it is the future I should start to understand it now :)
index.php:
<?php
// Setup document:
include('config/setup.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $page_title; ?> - test site</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="wrap_overall">
<div class="header">
<?php include('template/header.php'); ?>
</div>
<div class="nav_main">
<?php include('template/nav_main.php'); ?>
</div>
<div class="content">
<?php //include('content/'.$pg.'.php');
// the database connection, our query
$q = "SELECT * FROM pages WHERE page = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
if (!$r) {
die('Invalid query: ' . mysql_error());
}
$page = mysqli_fetch_assoc($r);
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content_body">'.$page['body'].'</div>';
?>
</div>
<div class="footer">
<?php include('template/footer.php'); ?>
</div>
</div>
</body>
</html>
setup.php:
<?php ## Setup Document
// host(or location of the database), username, password, database name
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "localhost";
$username = "atomcmsadmin";
$password = "uniCi2i";
$dbname = "Atom_CMS";
//Connecting to your database
$dbc = mysqli_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysqli_select_db($dbname);
//include('functions/sandbox.php');
if ($_GET ['page'] == '') {
$pg = 'home';}
else {
$pg = $_GET ['page']; }
$page_title = get_page_title($dbc, $pg);
?>
sandbox.php
<?php
// Sandbox Functions
function get_page ($dbc, $pg) {
// the database connection, our query
$q = "SELECT title FROM pages WHERE type = 1, page = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
$page = mysqli_fetch_assoc($r);
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content">'.$page['body'].'</div>';
}
function get_page_title ($dbc, $pg) {
$q = "SELECT title FROM pages WHERE type = 1, page = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
$page = mysqli_fetch_assoc($r);
return $page['title'];
}
?>
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
all you need to change is setting up the connection, check out the tutorial for the syntax
interacting with the database is still mostly the same
I think no one will do the job for you. But I can help you help yourself:
From your code, you'll need to learn these PDO methods:
PDO::__construct()
You'll replace mysqli_connect() and mysqli_select_db() with that.
PDO::prepare(), PDOStatement::bindValue() and PDOStatement::execute()
You'll replace mysqli_query() with them.
PDOStatement::fetch()
You'll replace mysqli_fetch_assoc() with that.
PDO::errorCode() and PDO::errorInfo()
You might want to use one of them or both to cover errors.
Also take a look at PDO book on the PHP manual. You'll learn all the stuff more easier than you think! Good luck!
I have been bugging by head over this, but couldn't get this to work. What's wrong with this?
$query="Select studentid,firstname,lastname,pts from students where collegeid=4";
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$pts=$row['pts'];
$name=$row['firstname']." ".$row['lastname'];
$rank= mysql_num_rows(queryMysql("Select distinct pts from students where pts>=$pts"));
echo<<<_END
<a href="student_profile.php?studentid=$row[studentid]" style="text-decoration: none;">
<div class="apps_each your_rank">
<span style="margin-right:5px;">$rank</span>
<div class="dp_small_c"><img class="dp_small" src="upload/$row[studentid].jpg"/></div>
<span class="apps_names">$name</span>
<div style="float:right">
<img src='pts.png' /><span>$row[pts]</span>
<img src='level.png' /><span>Level 1</span>
</div>
</div>
</a>
_END;
The error:
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 '' at line 1.
Surprisingly, below one(removing the WHERE clause) works. Why?
$row=mysql_fetch_array(mysql_query("Select studentid,pts,firstname,lastname from students"));
Table structure:
Everything's fine with table and its columns, because this query works everywhere else, only not here!
You mentionned in the comments that you wanted to use PDO. Here's what you can try:
$username = "enterUsername";
$password = "enterPass";
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$query = $conn->prepare("Select studentid,pts,firstname,lastname from students where collegeid=:id");
$query->execute(array(
':id' => 4
));
// get errors if there are
$errors = $query->errorInfo();
echo "<pre>";
print_r($errors);
echo "</pre>";
$results = $query->fetch(PDO::FETCH_ASSOC); // can also be fetchAll if you have more than 1 row.
// to test and check results
echo "<pre>";
print_r($results);
echo "</pre>";
if $query in the question returns an empty row, then the variable beneath it remained unassigned - i.e., $pts and $name have no entities.
However, the query below them uses the variable $pts, which presumably has to store some value - which, when not, throws the above posted MYSQL error. The use of function queryMysql() for this query further clears the issue, as it was defined as below:
function queryMysql($query)
{
$result=mysql_query($query) or die(mysql_error());
return $result;
}
Hence, the MySql error.
I would use this library for all MySQL querying - http://www.meekro.com.
Your select query becomes like this:
// Load Library
require 'meekrodb.2.2.class.php';
// Setup DB Connection
DB::$user = 'my_database_user';
DB::$password = 'my_database_password';
DB::$dbName = 'my_database_name';
DB::$host = '123.111.10.23';
// Where clause
$collegeid = 4;
// Exec Query
$row = DB::queryFirstRow("Select studentid,pts,firstname,lastname from students where collegeid = %d", $collegeid);
src: http://www.meekro.com/docs.php#anchor_queryfirstrow
I am brand new to php/mysql, so please excuse my level of knowledge here, and feel free to direct me in a better direction, if what I am doing is out of date.
I am pulling in information from a database to fill in a landing page. The layout starts with an image on the left and a headline to the right. Here, I am using the query to retrieve a page headline text:
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row["banner_headline"];
}
?>
This works great, but now I want to duplicate that headline text inside the img alt tag. What is the best way to duplicate this queries information inside the alt tag? Is there any abbreviated code I can use for this, or is it better to just copy this code inside the alt tag and run it twice?
Thanks for any insight!
You are, as the comment says, using deprecated functions, but to answer your question, you should declare a variable to hold the value once your retrieve it from the database so that you can use it whenever your want.
<?php
$result = mysql_query("SELECT banner_headline FROM low_engagement WHERE thread_segment = 'a3'", $connection);
if(!$result) {
die("Database query failed: " . mysql_error());
}
$bannerHeadline = "";
while ($row = mysql_fetch_array($result)) {
$bannerHeadline = $row["banner_headline"];
}
echo $bannerHeadline; //use this wherever you want
?>
It is hard to help without knowing more. You are pumping the results into an array, are you expecting to only return one result or many banner_headline results? If you will only ever get one result then all you need to do is something like this:
PHP:
$result = mysql_query("
SELECT `banner_headline`
FROM `low_engagement`
WHERE `thread_segment` = 'a3'", $connection) or die(mysql_error());
// This will get the zero index, meaning first result only
$alt = mysql_result($result,0,"banner_headline");
HTML:
<html>
<body>
<!--- Rest of code -->
<img src="" alt="<?php echo $alt ?>">
On a side note, you should stop using mysql-* functions, they are deprecated.
You should look into PDO or mysqli
What is causing my php code to freeze? I know it's cause of the while loop, but I have $max_threads--; at the end so it shouldn't do that.
<html>
<head>
<?php
$db = mysql_connect("host","name","pass") or die("Can't connect to host");
mysql_select_db("dbname",$db) or die("Can't connect to DB");
$sql_result = mysql_query("SELECT MAX(Thread) FROM test_posts", $db);
$rs = mysql_fetch_row($sql_result);
$max_threads = $rs[0];
$board = $_GET['board'];
?>
</head>
<body>
<?php
While($max_threads >= 0)
{
$sql_result = mysql_query("SELECT MIN(ID) FROM test_posts WHERE Thread=".$max_threads."", $db);
$rs = mysql_fetch_row($sql_result);
$sql_result = mysql_query("SELECT post FROM test_posts WHERE ID=".$rs[0]."", $db);
$post = mysql_fetch_row($sql_result);
$sql_result = mysql_query("SELECT name FROM test_posts WHERE ID=".$rs[0]."", $db);
$name = mysql_fetch_row($sql_result);
$sql_result = mysql_query("SELECT trip FROM test_posts WHERE ID=".$rs[0]."", $db);
$trip = mysql_fetch_row($sql_result);
if(!empty($post))
echo'<div class="postbox"><h4>'.$name[0].'['.$trip[0].']</h4><hr />' . $post[0] . '<br /><hr />[Reply]</div>';
$max_threads--;
}
?>
</body>
</html>
First, I'd suggest completely getting rid of the extraneous HTML bits. Then, build up your code slowly, line-by-line to see if you can find the offending line. So write a script that just connects to the database and see what happens.
If you find for example that this code...
<?php
$db = mysql_connect("host","name","pass") or die("Can't connect to host");
mysql_select_db("dbname",$db) or die("Can't connect to DB");
?>
...is causing the freeze on its own, then it could easily be a problem with the MySQL server.
However, if the browser itself is crashing, that sounds like an issue with your system rather than something that PHP or MySQL is doing...
Try this 1 SQL query instead of those 1 + (4 * n) queries:
SELECT MIN(ID), post, name, trip FROM test_posts GROUP BY Thread
Maybe a LIMIT 50 (or whatever max # of threads to return) at the end as well, that could be a lot of data.
You can just loop over the results of this query instead of $max_threads and all the extra db calls, via while ($row = mysql_fetch_row($sql_result)) { /* echo(...); */ }.
Not sure that's exactly the same as what you're trying to fetch without knowing more about the data (getting the root post of each thread in a forum?), but it should be pretty close.
(P.S.: if that's a threaded 2ch-style forum deal, I'm not sure that's an ideal db design. A parent-child adjacency list might be better than maintaining a number count for each thread. Just a guess though.)
I'm thinking it's because you're hitting the sql database 4 times per loop. Is there any way you can maybe access it all at once, and then parse the incoming data from there?
$dbsql = 'SELECT * FROM my_database';
$result = mysql_query($dbsql);
while($row = mysql_fetch_array($result)) {
// Parse information here, rather than
// accessing the database for individual variables...
}
Something like that.
Update:
Other than what I've already said (and you've dismissed) all I see are some here & there coding quirks:
This part didn't have a space between echo and the string. The 'hr' element didn't have a starting bracket.
echo '<div class="postbox"><h4>'.$name[0].'['.$trip[0].']</h4><hr>' . $post[0] . '<br /><hr />[Reply]</div>';
'while' Shouldn't be capitalized.
while($max_threads >= 0)
Again, clean code is a good place to start, but that's all I've got, personally. I just recently cleaned up my own site, which was crashing IE (and no other browser), simply because it had too many markup errors. Hope it helps.
Maybe you can scatter calls to this simple function in yer code:
function of($required)
{
$args = func_get_args();
var_dump($args);
ob_flush();
flush();
}
of(__LINE__, $max_threads);
You can also use something like this for your queries:
function mydb_query($query, $db = null)
{
$args = func_get_args();
$result = call_user_func_array('mysql_query', $args);
if (!$result) {
of(array(__FUNCTION__), mysql_error(), $sql);
//return something else?
}
return $result;
}
$result = mydb_query("SELECT post, name, trip FROM test_posts WHERE ID = (SELECT MIN(ID) FROM test_posts WHERE Thread={$max_threads})", $db);
You should use mysqli/PDO/framework with support for prepared statements.
Probably the script is exceeding the maximum server execution time threshold, try this on the top of your file to confirm this:
ini_set('max_execution_time', '180');