I have created a website which gets data from two 'different' MySql database tables. The tables have identical layouts (so the numbers in each table differs but 100% similar in ID's and column names). Now I am a complete self-made programming noob so bear with me in the following.
On the websites front page I display some data from both of the two tables. The way I do this is by creating a variable ($tableName) that holds the name of the table I need. This variable is then used for generating the necessary data in another file (data.php) and then displaying that data on the front page by the file design.php. This process is replicated for all tables in the MySql database. (below is a very simplified format).
Frontpage.php:
<?php
include('../connection.php');
?>
<?php
$tableName = table1;
include('../Data.php');
include('../Design.php');
?>
<?php
$tableName = table2;
include('../Data.php');
include('../Design.php');
?>
.....(etc.)
Data.php:
$query = "SELECT * FROM {$tableName} WHERE ID = 1";
$result = mysqli_query($conn, $query) or die('error');
while($data = mysqli_fetch_array($result)) {
For ($n = 0; $n < 1; $n++){
$dataVariable = $data["columnname"];
}
}
Design.php
<?php echo $dataVariable; ?>
So what happens is that the user goes to the $dataVariable link and is then sent to Ultimate.php which also includes the Data.php file in order to display a hell-uv-alot of data. I therefore have to again declare the $tableName variable in the Ultimate.php file and then duplicate the Ultimate.php file for every single table there is in the MySql database and change href-link in the Design.php file. (very annoying).
My question is: how can I pass on my $tableName variable from the href on the front page to Ultimate.php? I have searched on here and found a way which includes $tableName to the URL opened on Ultimate.php whereafter I use $_GET inside Ultimate.php to collect it. For some reason I couldn't make that work - and i don't know if this is at all a solid way to solve things in my case.
More importantly: I have never worked with programming before so if anyone can advise me whether I am setting this up most efficiently or not that would also be great! I very much welcome links to guides/tutorials which you think might benefit me at this point!
Thanks a lot in advance!
<?php echo $dataVariable; ?>
Then at the top of Ultimate.php:
<?php
$var = $_GET['var'];
?>
This takes the variable off the browser
http://www.example.com/Ultimate.php?var=yourvariable
You can pass variables from a hyperlink to another page using GET.
hyperlink text
$_GET['key']
http://php.net/manual/en/reserved.variables.get.php#refsect1-reserved.variables.get-examples
Related
I'm having trouble with my php code. I have a table in my DB and every entry has a name, type, location etc. The basic idea is that after entering the name from the previous page (that's why there's a POST variable at the start of the code), you get transfered to this page and it prints the corresponding type. The problem is that even though I'm sure the code is correct and I've tried a few different solutions (I've been searching for a while in the forum), I can't print the type variable.
<?php
$k = $_POST['sub1'];
$con = mysqli_connect("localhost","root","","qr code");
$query = mysqli_query($con, "SELECT type FROM array1 WHERE name ='".$k."'");
while($row = mysqli_fetch_assoc($query)) {
echo $row['type']; }
?>
Any ideas? It's probably a very simple solution, but I'm totally stuck now so I'm sorry if it's too basic :P
So, I'm learning PHP and MySQL, but I have run into a little problem here.
I do lack some information, so this will be very helpful to me =)
I do a query against my database, and get a result. This result is all my image files to be listed.
$fileSQL = $mysqli->query("
SELECT *
FROM content
WHERE projID=$projectID
");
So, if I want to list all my files as thumbnails on my page I do this:
<?php while($row = $fileSQL->fetch_assoc()){ ?>
<img src="assets/<?=$row['contentFull']?>" id="thumbImg"
onclick="document.getElementById('mainImage').src=this.src" width="110px" height="62px"/>
<?php } ?>
Now, this works fine, of course. It loops through all the rows while adding a for each of them.
However, I do have a main image too, where I need to show the first thumb in full (for this example I use contentFull both for thumbs and fullsize).
Now, how do I get the first row's contentFull, without making the while loop start from row nr.2?
And in general; what is the best way to do in these situations? Store the result to an array first, so I can access it easily, or what is the "normal" way of doing it? =)
What I need:
Do a query
Set the main image (using contentFull from the first
image/content in my sql result)
Then draw all the images in the
result to thumbnails (including the first that are already shown as
the main image)
Thanks in advance, and please let me know if you need more information =)
One simple options would be to do this:
<?php
$first = null;
while($row = $fileSQL->fetch_assoc()) {
if(!isset($first)) $first = $row;
?>
<img src="assets/<?=$row['contentFull']?>" id="thumbImg"
onclick="document.getElementById('mainImage').src=this.src" width="110px" height="62px"/>
<?php } ?>
Now you have the first row stored in a variable to use, without having to store all the results in an array. If for some reason you want all rows stored in an array you could simply do this:
<?php
$rows = array();
while($row = $fileSQL->fetch_assoc()) {
$rows[] = $row;
//rest of code
}
?>
Then you could access first row by referencing $rows[0]
Another option would be to not use php to populate the full image. Instead use a javascript call to populate the first image.
I think you could take your first picture outside the while loop:
$row = $fileSQL->fetch_assoc(); // the first picture
if($row){
// show first image if it exists
}
while ( $row = $fileSQL->fetch_assoc()) // etc.
Probably code for larger image is different than for others, so it could be reasonable. If not, consider defining a function, or use a counter (or flag like in Pitchinnate's answer).
These two pull out data from two different data bases. It's all good undtil I repeat the first one for a second time (to pull out the count of comments of more than one article), the second script (pulls out the data about vistis to the articles and arranges them by desc. order) stops working (no error, nothing, just doesn't provide an output). I'm no expert (yet) in the PHP so I can't seem to figure what is wrong in this sutuation. Maybe some of you will notice some obvious flaw which makes 'em interfere like that?
1st script (comment count). Just to make it clear: I don't use "define", the second time I use it for a diff. article. It's needed just in the first one to work.):
<?php
$id = "1"; //The ID of the page. You can get this from Manage -> Pages.
define('IN_COMMENTICS', '1');
require ($_SERVER['DOCUMENT_ROOT'].'comments/includes/db/connect.php');
$query = mysql_query("SELECT * FROM `".$cmtx_mysql_table_prefix."comments` WHERE is_approved = '1' AND page_id = '$id'");
$total = mysql_num_rows($query);
echo $total;
?>
Second script (counts visits):
<?php
$sql = "SELECT pagename, hits, title FROM counts ORDER BY hits DESC LIMIT 10";
$res = mysql_query($sql);
if(!$res) {
// oops - exit?
}
while(list($page,$hits,$title) = mysql_fetch_row($res)) {
echo "<li><a href='$page'>$title</a> $hits</li>";
}
?>
The only thing I could see is that you are using the function require to include you database initializing file, AND its executed two times which my create problems to causing this issue you are facing.
Perhaps, consider using require_once function which will take care to not load the database initializing file more than one time.
To conclude, I would suggest to do the following
Replace this:
require ($_SERVER['DOCUMENT_ROOT'].'comments/includes/db/connect.php');
by this:
require_once ($_SERVER['DOCUMENT_ROOT'].'comments/includes/db/connect.php');
I have a mySQL database table setup called site.
Rather than qet the column headings to produce a PHP object of values I want to produce data from the rows.
TABLE: site
:::field:::::value:::::
url www.example.com
name example site
etc Example Etcetera
So I want to be able to get this information from the server by calling the column name I want and the row I am after. I want to do this for all fields in site as I don't want to do multiple calls for the various different rows in site; I'd rather store all the information from the beginning in the object:
eg. <? echo $site['url']; ?>
I created this put it appears to be causing an error:.
$sql = "SELECT * FROM `site`";
$site[];
foreach($sodh->query($sql) as $sitefield){
$site[$sitefield['field']] = $sitefield['value'];
}
Obviously I've missed something. ¿Any idea as to what?
$site[];
should be
$site = array();
I've searched far and wide and every CMS tutorial out there either doesn't explain this at all or gives you a huge chunk of code without explaining how it works. Even on stack overflow I can't find anything close to the answer, though I'd be okay with eating my words if someone could point me to the answer.
I am using PHP and mysql for this project.
I am building a CMS. Its extremely simple and I understand every concept I think I'll need except how to dynamically generate pages and page links. The way I want to do it is by having a database table that stores the name of a page and the main content of the page. That's all. Then I'd just call a script to pull the main content of a page into whatever page I happen to call. No big deal, right? Wrong.
Here's the problem. If I were to do this then I'd have to create a file for every page I want to create that calls the script that pulls the content from the correct database row. So I could add all sorts of page names and contents into the table but I don't know how to call them without manually creating new files each time I want to link to a new page.
Ideally there'd be a script that creates links to pages based on the page name row of the DB table as the pages are created. But how do you get those links with the ?=pageName at the end? If I just knew how that worked then I could figure the rest out.
UPDATE
The second answer really confirmed everything I thought I had to do but there is one catch. My plan now is to split up all the code into a series of functions and either include or require them in different templates that will be used to format the way pages are displayed. I need one look for the home page and one other design for the rest of the pages. I'm thinking that I'll have a function that says if ID is 0 then call this page template.php else call this other template file.php. But how do I pass the required variables to these new files? Do I just include the index.PHP page in them?
Bill your actually on the right track. Almost all web software today does extensive URL processing. Traditionally you would have php pages on your web root and then utilize the query string in the URL to refine the page's output. You have already arrived at why this might not be desired. So the popular alternative is the Front Controller design pattern. Basically we funnel every request to your index.php page and then route the request to internal pages or apps outside the web root. This can get complicated fast and everybody seems to implement this pattern in unique ways.
We can utilize this pattern without the routing by simply putting our app in the index page. The script below shows an example of what your trying to do in the simplest of ways. We basically have one page with our script. We can request the virtual pages by changing the id query string in our url. For example www.demo.net/?id=0 can be utilized as an index to your site. This should be the same as www.demo.net without the 'id' query. Just keep solving those problems one by one even if you don't know what the problem is. Once you start looking at other peoples code, then you can start seeing how other people solved the same problems you have.
The solution below will get you started, but then what do you do when you want an admin page? How do you authenticate the user? Do you duplicate alot of the code for yet another page? If your serious about your CMS then your going to want to implement some kind of framework underneath it. A framework to process the url, route to your application, load configuration files, and probably manage your database connection. Yea it gets complicated, but not if you solve each problem one at a time. Utilize classes or functions to share code to start. At the very least include a common "bootstrap" file at the top of your page to initialize common functionality such as a database connection. Read Stack Overflow just to keep up with whats going on. You can learn alot of terminology and probably find some answers to questions you didn't even know you wanted to ask.
Below assume we have a table with the following fields:
page_id
page_name
page_title
page_body
<?php
//<--------Move outside of web root-------------->
define('DB_HOST', 'localhost');
define('DB_USER', 'cms');
define('DB_PASS', 'changeme');
define('DB_DB', 'cms');
define('DB_TABLE', 'cms_pages');
//<---------------------------------------------->
//Display errors for development testing
ini_set('display_errors','On');
//Get the requested page id
if(isset($_GET['id']))
{
$id = $_GET['id'];
}
else
{
//Make page id '0' an index page to catch all
$id = 0;
}
//Establish a connection to MySQL
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
//Select the database we will be querying
mysql_select_db(DB_DB, $conn) or die(mysql_error());
//Lets just grab the whole table
$sql = "SELECT * FROM ".DB_TABLE;
$resultset = mysql_query($sql, $conn) or die(mysql_error());
//The Select Query succeeded, but returned 0 result.
if (mysql_num_rows($resultset)==0)
{
echo "<pre>Add some Pages to my CMS</pre>";
exit;
}
//This is our target array we need to fill with arrays of pages
$result = array();
//Convert result into an array of associative arrays
while($row = mysql_fetch_assoc($resultset))
{
$result[] = $row;
}
//We now have all the information needed to build our app
//Page name - Short name for buttons, etc.
$name = "";
//Page title - The page content title
$title = "";
//Page body - The content you have stored in a table
$body = "";
//Page navigation - Array of formatted links
$nav = array();
//Process all pages in one pass
foreach($result as $row)
{
//Logic to match the requested page id
if($row['page_id'] == $id)
{
//Requested Page
$name = $row['page_name'];
$title = $row['page_title'];
$body = $row['page_body'];
$page = "<b>$name</b>";
}
else
{
//Not the requested page
$page = $row['page_name'];
}
//Build the navigation array preformatted with list items
$url = "./?id=" . $row['page_id'];
$nav[] = "<li>$page</li>";
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>SimpleCMS | <?php echo $title; ?></title>
</head>
<body>
<div>
<div id="navigation" style="float:left;">
<ul>
<?php
foreach($nav as $item)
{
echo $item;
}
?>
</ul>
</div>
<div id="content"><?php echo $body;?></div>
</div>
</body>
</html>
I think you need to read about $_GET.
I also recommend a decent PHP book. Forget online tutorials; they are (for the most part) utterly useless.