Im using Switch statment to change the content of my page, like this:
$id=$_GET['id'];
$n = $_GET['n'];
switch ($id) {
case 0:
include("news.php");
break;
case 1:
include("newsdetail.php?n=".$n);
break;
default:
include("news.php");
}
In news.php i show all the existing news like this:
while($myrow = mysqli_fetch_array($result)){
echo "<table>
<tr>
<td><img width='200' heigth='115' src='images/".$myrow['smallimage'].".jpg'/></td>
<td>
<b>".$myrow['title']."</b>
<br />
<i>By ".$myrow['author'].", ".$myrow['date']."</i>
<br />
".$myrow['preview']."<br>
<a href='index.php?id=1&n=".$myrow['id']."'><b>READ</b></a>
</td>
</tr>
</table>";
}
And insidetails.php:
$idnews = $_GET['n'];
$sql = "SELECT * FROM news WHERE id='$idnews'";
$result = mysqli_query($db,$sql);
while($myrow = mysqli_fetch_array($result)){
echo $myrow['title']."<br>
<i>Por ".$myrow['author']."</i><br>
".$myrow['date']."<br>
<img src='images/".$myrow['bigimage'].".jpg'>
".$myrow['body']."";
}
When I try this I get an url like .../index.php?id=1&n=1 but shows no content. Everything works fine when tested alone.
Is it possible to make something like this and mak it work?
You can't do includes like this:
case 1:
include("newsdetail.php?n=".$n);
break;
This will have PHP trying to find a file called newsdetail.php?n=1, so there's no content showing up.
But there's no need to do it that way; your included file can still access the $_GET variables - like $_POST and so on, they're global, and so can be accessed anywhere in your code.
And just a note to be wary; you're passing a value from $_GET directly into a query. This opens you up to SQL injection issues. You should look at using mysqli_ or PDO, both of which help you write code that's a lot more secure.
There are quite a few problems with your code. I will try to address them one by one.
First of all, you are widely open to a SQL Injection. Always use
prepared statements and parameterized queries.
You are mixing SQL with your logic and even presentation code. You should put that in completely different classes as each class should have just one responsibility. This also makes your code much more maintainable and you can reuse your code instead of copy pasting it (violating the DRY principle). An example of this concept is the MVC pattern.
To access the different parts of your application you should use the front controller pattern (it seems like you are already doing that). So that is good. Now you could use an autoloader which will automatically load the required files. I recommend using namespaces and using a PSR-0 autoloader.
Now you still need to route the request to the right class method (controller if you are using MVC). I recommend you use one of many available libraries like that, for example klein. If you want to write your own, at least look at the code of some routing libraries and see how they are doing it.
I know this is a lot but I hope you take the time to learn about the concepts I described above. Don't worry if you don't understand everything the first time. And if you have any questions, ask away.
Related
Is it possible to submit a query without updating the URL?
On a dictionary, I want to do first one simple query: www.example.com/?q=word
On the result page there will be a button with which I want to search for more results with another query.
This second query will be done normally with www.example.com/more.php?q=word.
That code would look as follows:
<button onclick="window.location.href = 'more.php?q=<?php echo "$trimmed"; ?>';">search for more results</button>
However, I want that the URL remains unchanged so that the next dictionary query starts again with a simple query. In other words, I want to hide the part "more.php" from the URL.
Assuming that your www.example.com?q=word points to the index.php.
Assuming also that your more.php contains functions.
Assuming as third, that your index.php returns something displayable in the browser even if there is no GET-parameter i.e. the initial page call.
Doing so, a really simple solution would be to fire every query against the index.php.
There you can handle every query, even different types, based on a new GET-parameter type use use.
#index.php
require 'more.php';
// do something here to validate the parameters you use
switch($_GET('type')) {
case 'simple':
return simpleCall();
break;
case 'more':
return additionalInfo();
break;
}
function simpleCall() {
// do stuff here
// access $_GET for other paramters
}
#more.php
function complexCall() {
//do complex stuff here
}
Finally, your HTML would look something like this
<button onclick="window.location.href = '/?type="more"&q=<?php echo "$trimmed"; ?>';">search for more results</button>
Until you get more than these two types it becomes cluttering at your switch-statement.
For this reason, it would be a good idea to think about different solutions like:
having a routing system like this https://medium.com/the-andela-way/how-to-build-a-basic-server-side-routing-system-in-php-e52e613cf241
using asynchronous calls from your frontend with the help of JavaScript to call to different PHP files on the server but stay on the same page in the frontend. This will immediately lead to some kind of API. But this is generally not the badest idea.
Please validate your parameters regardless if POST or GET before you do anything with them in the rest of your code. Having the example of a dictionary sounds extremely like to query a database where SQL injection is, for example, a big thing if data us used unchecked.
I hope this helps a bit.
I am building a website using php. I would want to separate the php from the html. Smarty engine, I guess does that, but right now its too complicated for me. Looking for a quick fix and easy to learn solution, one which is an accepted standard as well. Anyone helping please.
Consider frameworks or choose a template engine
Use a framework. Depending on your project, either a micro framework like Slim or something more complete like Laravel.
What I sometimes do when writing complex systems with quite much php code is separating it the following way (don't know your exact project, but it might work for you):
You create a php file with all the functions and variables you need. Then, you load every wepgage through the index.php file using .htaccess (so that a user actually always loads the index.php with a query string). Now, you can load the html page using file_get_contents (or similar) into a variable (I call this $body now); this variable can be modified using preg_replace.
An example: In the html file, you write {title} instead of <title>Sometext</title>
The replacement replaces {title} with the code you actually need:
$body = str_replace('{title}', $title, $body);
When all replacements are done, simply echo $body...
Just declare a lot of variables and use them in the template:
In your application:
function renderUserInformation($user)
{
$userName = $user->userName;
$userFullName = $user->fullName;
$userAge = $user->age;
include 'user.tpl.php';
}
In user.tpl.php:
User name: <?=$username?><br>
Full name: <?=userFullName?><br>
Age: <?=$userAge?>
By putting it in a function, you can limit the scope of the variables, so you won't pollute your global scope and/or accidentally overwrite existing variables.
This way, you can just 'prepare' the information needed to display and in a separate php file, all you need to do is output those variables.
Of course, if you must, you can still add more complex PHP code to the template, but try to do it as little as possible.
In the future, you might move this 'render' function to a separate class. In a way, this class is a view (a User View, in this case), and it is one step in creating a MVC structure. (But don't worry about that for now.)
Looking for a quick fix and easy to learn solution
METHOD 1 (the laziest; yet you preserve highlighting on editors like notepad++)
<?php
// my php
echo "foo";
$a = 4;
// now close the php tag -temporary-
// to render some html in the laziest of ways
?>
<!-- my html -->
<div></div>
<?php
// continue my php code
METHOD 2 (more organized; use template files, after you passed some values on it)
<?php
// my php
$var1 = "foo";
$title = "bar";
$v = array("var1"=>"foo","title"=>"bar"); // preferrable
include("template.php");
?>
template.php
<?php
// $var1, $var2 are known, also the array.
?>
<div>
<span> <?php echo $v["title"]; ?> </span>
</div>
Personally, i prefer method 2 and im using it in my own CMS which uses lots and lots of templates and arrays of data.
Another solution is of course advanced template engines like Smarty, PHPTemplate and the likes. You need a lot of time to learn them though and personally i dont like their approach (new language style)
function renderUserInformation($user)
{
$userName = $user->userName;
$userFullName = $user->fullName;
$userAge = $user->age;
include 'user.tpl.php';
}
I'm trying to figure out what is the best way to clone/template HTML that is frequently repeated in my web app. For example, I have a voting <form> (see below) that needs to be located on several pages.
Two ways I thought of doing this:
a function call, e.g., voteForm($action, $user_id, $formType, $success);
an include statement, e.g., include '/myApp/views/voteForm.php'
I prefer an include statement b/c:
Then I don't have to decide on the function's parameters which may change over time forcing me to rewrite the function calls everywhere they exists in my app. With the include statement, I can just use the variables as they are wherever I put the included php file (avoiding redeclaring them which is a pain b/c there are often lots of variables).
I can write the HTML in HTML and not as a PHP string where I have to deal with escaping characters/json_encode issues.
Should I reconsider using include instead function() for any reasons (e.g., performance)? Are there are other templating solutions I'm not thinking of?
<form action="<?=$action?>" method='post' data-form-data='{'formType': '<?=$formType?>', 'success': '<?=$success?>'} >`
<input type='hidden' value='<?=$user_id?>' name='user_id'>
<input type='radio' value='1' name='vote'>
<input type='radio' value='-1' name='vote'>
</form>
It's really up to you--you could have a hybrid of a function that calls include for you (setting up any necessary variables that the include file may need for display purposes). e.g.
function createForm($action,$foo,$bar){
$form_action = $action;
$form_foo = $foo;
include('templates/form.inc');
}
As far as performance, there's no huge benefit that I'm aware of. Although If you're looking for a better way for templating, you may want to look at smarty or some other system that handles most of the 'tough work' for you.
Just keep in mind that when you have code outputting HTML you no longer have a separation of concerns. That is to say that if you decide to change the look and feel of the site at a later date you're not looking through just .inc (or whatever extension you've used) files, but now both .inc and .php files to apply changes.
I would try to avoid putting HTML into function calls. I think what your trying to achieve here would be best suited to an include statement - based on personal preference.
As for performance - it's hard to tell but you could use a PHP Profiler like XDebug to see whether a function or include is the most efficient.
http://xdebug.org/docs/profiler
For big blocks of generated HTML, I'd recommend using includes. I prefer to use function calls to get specific bits of data back.
The again, this is personal preference and cannot be answered with a truly 'correct' answer.
In terms of performance, I would guess not much difference at all unless you're making thousands of calls on each one in one go.
Hope that helps.
So I'm working on a PHP app and trying to make everything moduler. I have an index.php file that includes other php files. The first file included is settings.php which has my postgres credentials defined so they can be accessed elsewhere. The second file is connect.php that has a function you can pass sql to and it will return $result. The third file has functions that call the sql function and receive $result and parse it. In the third file, I can read the results of the $result however if I try if($result) it breaks and isset/empty have no effect.
Anyone have any ideas on a way to make this work, or is my structure just terrible?
Thanks so much!
Mike
let's say you have the following three files:
inc1.php
<?php
$foo = 'hello';
?>
inc2.php
<?php
echo $foo;
?>
main.php
include('inc1.php');
include('inc2.php');
it should echo "hello". however, passing variables around among files is a bad idea, and can lead to a lot of confusing, hard-to-follow code. If you need to pass variables around, use functions and/or objects so that you can at least see where they are coming from.
beyond that though, it's difficult to tell exactly what your problem is without seeing the code in question.
I would really try to switch to OOP. This makes things a lot of easier. If you just have to deal with classes, their methods and attributes you only have to include the classes and not this choas of functions. So I would recommend, give it a go ...
I started working with php and mysql today. Basically, what I have, is an empty page with pieces that I fill in from looking up an id in a database. So on my home page I have an url that looks like this:
<a href="content/display.php?id=id1">
And then in my display.php I have this:
<?php
include '../includes/header.php';
$id = $_GET['id'];
$mysqli = new mysqli('localhost','username','password','dbname');
if($result = $mysqli->query("SELECT * FROM portfolio WHERE id='".$id."'"))
{
while($row = $result->fetch_object())
{
$head = $row->head;
$img1 = $row->img1;
$img2 = $row->img2;
$img_url = $row->imgurl;
$img_thumb = $row->imgthumb;
$vid = $row->vid;
$swf = $row->swf;
$url = $row->url;
$url_text = $row->urltext;
$text = $row->text;
}
}
else echo $mysqli->error;
?>
It's a sparse table in that not all of those fields will have information (many might be null). Basically they contains file names and then in the html I have code that looks like this:
if(isset($img1))
{
echo '<img src="images/'.$img1.'" />';
}
A couple of questions,
Is this the best way to do this?
Everytime I visit display.php, I am reopening a database connection right? That can't be good...
I chose to put the names of the files in the database, rather than entire path names, or even the actual files themselves, figuring that, if I change the name of the file I can go into the database and update it for the file I want to change. If I change the path, I can just change it once in the html. Is that the best idea?
Thanks!
1) No, although that's the easiest way for beginning. After you feel comfortable with basics, you should spend some time considering different approaches to application structure. Most important rule is to separate concerns. Don't mix database code with business logic code with presentation code. But like I said, it's not something you should worry about on your first day. For now just learn basics.
2) There's no other way actually. For a web application each request from browser is like an individual run of application. There is a possibility to use so called persistent database connections, but just like in previous point, that's something you should not deal with on your first day, as they require specific configuration of your web server. For the time being just use normal connections.
3) That's pretty sensible idea. You could also define your image path as a PHP constant, so that in case a change is needed, you only change this one constant.
4) What sAc says in his answer is very important. Read about SQL injections and how to prevent them.
You are vulnerable to SQL injection, properly type cast your variables:
$id = (int) $_GET['id'];
Use functions such as mysql_real_escape_string or even better use:
Prepared Statements
SQL injection & prepared statements are already mentioned. An addition to that would be:
else echo $mysqli->error;
Change that to:
else trigger_error($mysqli->error,E_USER_ERROR);
Why you ask? Because visitors should have no idea about your database, and cannot fix the error, so they plain shouldn't see it. This way, you can safely develop with display_errors on, and on the live site display_errors is off, and you log_errors in an error log.
Looks like you have good handle on what you want to do. I don't know how much development background you have, but it would be a good idea to start learning about MVC's in php like CakePHP, Fuse, or even Zend Framework(bleh!!!). I'll save you time on more robust applications by pre defining all your basic db interface, template handling, session handling, and let you worry about higher level problems, like what's for lunch! :)