I know this is probably a really amateur question, but I can't figure this out and I don't know much about PHP or MySQL.
So I have a really simple script that basically allows a user to submit a couple lines of text and their zipcode, then it write it to a database and returns the results on the site. It's a shoutbox essentially.
My client wants the users to be able to filter the results by zipcode. So I have it all setup, and I have a search input where people type in their zipcode, search, and then the PHP returns the submissions from that zipcode.
While I can get the results to show by themselves echoed from the PHP script, how do I get them to display within a specified div within the site? I want it essentially to store a variable, the zipcode, that a user search by, and then use that once the page refreshes to display an updated list that filters out the results that aren't from that zipcode.
Thanks so much for the help.
Chris
Without getting into rewriting etc.:
When you redirect your page, add a query at the end of it that is the zipcode making sure that you don't send any whitespace and that you have an input in a given format:
search.php?zipcode=90210
Then on your search results page, fetch the variable passed and work as usual:
$zipcode = $_GET['zipcode'];
make sure that the zipcode is properly escaped and filtered for nasties.
Make the HTML page a PHP page (usually by making the extension .php). Replace the target div's content with <?php stuff to get and print results ?>.
If you have PHP installed and configured on the web server, it will take certain files (usually those ending in .php) and run them through PHP's interpreter. The PHP interpreter is invoked anytime there is a <?php in the document and it stops parsing content anytime it meets a ?> within the <?php block.
For instance, to get a web page to print "Hello World!" into a div through PHP, I would do:
<div><?php
print 'Hello World!';
?></div>
OK, I figured it out. I just stored my answer in a SESSION variable so that I could call it in my other PHP files.
Now I have one file processing the request, creating the session and the variable, and then redirecting the page. Then I have a PHP included in the page that grabs the SESSION variable and plugs it into my mysql_query to return the proper result!
Not sure if this is the best way of doing it, but it's working.... If anyone knows of a more elegant solution I would love to know it.
Thanks,
Chris
I suggest you do some tutorials on using PHP and database retrieval with mysqli.
<?php
/* Connect to a MySQL server */
$link = mysqli_connect(
'localhost', /* The host to connect to */
'user', /* The user to connect as */
'password', /* The password to use */
'world'); /* The default database to query */
if (!$link) {
printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error());
exit;
}
/* Send a query to the server */
if ($result = mysqli_query($link, 'SELECT Name, Population FROM City ORDER BY Population DESC LIMIT 5')) {
print("Very large cities are:\n");
/* Fetch the results of the query */
while( $row = mysqli_fetch_assoc($result) ){
printf("%s (%s)\n", $row['Name'], $row['Population']);
}
/* Destroy the result set and free the memory used for it */
mysqli_free_result($result);
}
/* Close the connection */
mysqli_close($link);
?>
Related
I'm currently using Chatfuel to open the index.php-file of my website which sends the user the html code into his browser. There he can register and set up his account.
An example URL might look like this:
https://my.domain.com?key_value='123456789'
Depending on if that user is a new or a existing one, I wanna present him with a different form. In order to check so, I do a simple query to the MySQL db and see if the passed on key_value is already in the db and safe true or false to a boolean. Stating the obvious: If hes not an existing user, the 'empty' form with no values should show up. If he is registered he should see the information he filled in from last time.
My idea:
At the top of my index.php I do the check whether he's an existing customer or not (Note: This is working already). Then I want to use outputbuffering to alter the html-code depending on the boolean, before it is sent to the client.
My problem:
I developed the blueprint of the website in plain html (see code below). And OB only catches it as output if its within a string. Since I use " as well as ' in the document the string gets interrupted every few lines. Is there a simple workaround to this? Because the OB function is unable to access anything within the <html>...</html> tags.
Or do i need to use redirecting after the check (in my index.php) and create a separate form + script for both edit customer data and add new customer data?
<?php
//Connection stuff
// Prepare statment: !TODO: string needs to be escaped properly first
$query_string = "SELECT * FROM tbl_customer WHERE unique_url = '$uniqueurl'";
$query_rslt = mysqli_query($conn, $query_string);
if($query_rslt == FALSE)
{
// Failure
echo "<br> Oops! Something went wrong with the querying of the db. " . $conn->connect_error;
//Handle error
}
else
{
if ($query_rslt->num_rows > 0)
{
// Set boolean
$existing_customer = TRUE;
// Create an array called row to store all tuples that match the query string
while($row = mysqli_fetch_assoc($query_rslt)) {
//...
}
}
}
// Custom post processing function
function ob_postprocess($buffer)
{
// do a fun quick change to our HTML before it is sent to the browser
$buffer = str_replace('Testing', 'Working', $buffer);
// Send $buffer to the browser
return $buffer;
}
// start output buffering at the top of our script with this simple command
// we've added "ob_postprocess" (our custom post processing function) as a parameter of ob_start
if (!ob_start('ob_postprocess'))
{
// Failure
echo "<br> Oops! Something went wrong with output buffering. Check that no HTML-Code is sent to client before calling this start function.";
// Handle error
}
else
{
// Success
// This is where the string should get accessed before sending to the client browser
echo "Testing OB.";
}
?>
<!--DOCTYPE html-->
<html lang="en">
<head>
<meta charset="utf-8">
//...
</body>
</html>
<?php
// end output buffering and send our HTML to the browser as a whole
ob_end_flush();
?>
Output: "Working OB."
EDIT: I added source code example. This code won't compile.
Since, i can't comment, so i'll put some of my question here.
I dont really get the point, but give me a try, are you mean escaping string? you can use backslashes \ to escape string.
Like this "select from ".$dbname." where id = \"".$id."\"".
You can easily using addslashes($var) before adding the variable to the sql. like this
$id = addslashes($_POST['id']);
$sql = "select form db where id = '$id'";
If you mean checking the existent of the user to select which form to show in the page, why dont you do this?
if(userCheck()) {
?>
// here write the html code if user passed
<?php
} else {
?>
// here write the html code if user not passed
<?php
}
You can put userCheck() as global function or whereever you place it, as long as you can use it when you want to check the user before showing the form.
tl;dr: The thing I was looking for was a combination of file_get_contents() and object buffering.
file_get_contents() returns a string of a plain html-file of your choice. I could post a ton of explanation here or simply link you to phppot.com. The article offers you a directly executable demo with source (Download here). In case you wanna try it with a html file of yours, simply change the file path.
So once the whole html was converted into a string, I used the postprocessing function of OB to alter the string (= basically my html) if it's an existing user that came to alter his data. Then all the html-code (in a string still at this point) is sent to the client using ob_end_flush(). I will put up the actual code asap :)
I'm new to this and I know I'm probably doing this entire thing the wrong way, but I've been at it all day trying to figure it out. I'm realizing there's a big difference between programming a real project of my own rather than just practicing small syntax-code online. So, I lack the experience on how to merge/pass different variables/scopes together. Understanding how to fit everything within the bigger picture is a completely different story for me. Thanks in advance.
What I'm trying to do, is to make the function "selectyacht" output data in a different location from where it's being called (in viewship.php). The output data (in viewship.php) needs to be only certain fields (not everything) returned and those results will be scattered all over the html page (not in a table). In addition to that, I have this variable: "$sqlstatement" (in sqlconn.php) that I'm trying to bring outside the function because I don't want to repeat the connection function every time. I tried a global variable, as much as I shouldn't, and it thankfully it gave me an error, which means I have to find a better way.
Basically my struggle is in understanding how I should structure this entire thing based on two factors:
To allow the second conditional statement in sqlconn.php to be typed
as least often as possible for different "selectyacht" functions
that will come in the future.
To allow the connection instance in sqlconn.php to reside outside the function since it will be used many times for different functions.
Returning data in a different place from where it's being called in viewship.php because the call will be a button press, not the results to be shown.
This is probably very simple, but yet it eludes me.
P.S. Some of this code is a copy/paste from other resources on the internet that I'm trying to merge with my own needs.
sqlconn.php
<?php
$servername = "XXXXXXXX";
$username = "XXXXXXXX";
$password = "XXXXXXXX";
$dbname = "XXXXXXXX";
// Instantiate the connection object
$dbconn = new mysqli($servername, $username, $password, $dbname);
// Check if the connection works or show an error
if ($dbconn->connect_error) {
die("Connection failed: " . $dbconn->connect_error);
}
// Create a query based on the ship's name
function selectyacht($shipname) {
global $sqlstatement;
$sqlstatement = "SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
}
// Put the sql statement inside the connection.
// Additional sql statements will be added in the future somehow from other functions
$query = $dbconn->query($sqlstatement);
// Return the data from the ship to be repeated as less as possible for each future function
if ($query->field_count > 0) {
while($data = $query->fetch_assoc()) {
return $data;
}
}
else {
echo "No data found";
}
// Close the connection
$dbconn->close();
?>
viewship.php
<html>
<body>
<?php include 'sqlconn.php';?>
<!-- ship being selected from different buttons -->
<?php selectyacht("Pelorus");?>
<br>
<!-- This is the output result -->
<?php echo $data["Designer"];?>
<?php echo $data["Length"];?>
<?php echo $data["Beam"];?>
<?php echo $data["Height"];?>
</body>
</html>
Mate, I am not sure if I can cover whole PHP coding standards in one answer but I will try to at least direct you.
First of all you need to learn about classes and object oriented programming. The subject itself could be a book but what you should research is autoloading which basically allows you to put your functions code in different files and let server to include these files when you call function used in one of these files. This way you will be able to split code responsible for database connection and for performing data operations (fetching/updating/deleting).
Second, drop mysqli and move to PDO (or even better to DBAL when you discover what Composer is). I know that Internet is full of examples based on mysqli but this method is just on it's way out and it is not coming back.
Next, use prepared statements - it's a security thing (read about SQL injection). Never, ever put external variables into query like this:
"SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
Anyone with mean intentions is able to put there string which will modify your query to do whatever he wants eg. erase your database completely. Using prepared statements in PDO your query would look like this:
$stmt = $this->pdo->prepare("SELECT * FROM ships WHERE Name = :ship_name");
$stmt->bindValue(':ship_name', $shipname);
Now to your structure - you should have DB class responsible only for database connection and Ships class where you would have your functions responsible eg. for fetching data. Than you would pass (inject) database connection as an argument to class containing you selectYacht function.
Look here for details how implementation looks like: Singleton alternative for PHP PDO
For
'Returning data in a different place from where it's being called'
If I understand you correctly you would like to have some field to input ship name and button to show its details after clicking into it. You have 2 options here:
standard form - you just create standard html form and submit it with button click redirecting it to itself (or other page). In file where you would like to show results you just use function selectYacht getting ship name from POST and passing it to function selectYacht and then just printing it's results (field by field in places you need them)
AJAX form - if you prefer doing it without reloading original page - sending field value representing ship name via AJAX to other page where you use selectYacht function and update page with Java Script
I am doing this flash banners for multiple clients and one major request is to have some sort of counter so they know how many times the banner has been clicked.
I know how to do it in ActionScript 3.0, I make a simple var:int and i increase it +1 when a click is made on the banner. What do I do with the value of this var(say its 121) where do I store it online so its safe and can be changed by multiple flash banners(as3).
But how do I save this information so next time when the banner is loaded(on diffrent webpages) the number of clicks is whatever it was last time it was loaded.
Should I look into PHP for that ? I have no clue how to do this... some examples, tutorials, whatever works... would be much appreciated.(I am a designer, not programmer...please dont speak php-ish, or you know... :D)
I've googled a bit, and found some help, but i am still confused, and much of it its not AS3, I'm thinking maybe stuff has evolved a bit since the stuff that I found(2008)...
Thank you very much.
You'd have to store (and fetch) the value somewhere - either in the DB, in a text-file, ...
I'd go search for a tutorial on PHP+MySQL. If you don't like PHP-ish, you're probably better of finding another solution though :p
Example tutorial: http://www.freewebmasterhelp.com/tutorials/phpmysql
You need to store the data you want be retrievable/update-able from multiple clients, to be stored on a server.
You can use any server side language with a database.
Server Languages : PHP, ASP.net, JSP, ColdFusion
Database : MySQL, MSSQL, PostgreSQL, Oracle, DB2 etc..
Use whatever combination you are comfortable with.
In general:
You have a web app that increments the counter in the database
call the page using URLLoader from your AS3 banner.
Database
counter_table
-------------
counter INT
PHP File
$db = mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db('database_name');
mysql_query('UPDATE counter_table SET counter = counter + 1');
AS3 Banner
// url request with your php page address
var scriptRequest:URLRequest = new URLRequest("http://www.example.com/script.php");
// loader
var scriptLoader:URLLoader = new URLLoader();
// load page to trigger database update
scriptLoader.load(scriptRequest);
Do you also want to retrieve the value of the number of clicks in Banner ?
Easy solution (really not the best :) You should use one of the other answers.. anyways, make a php file that reads txt file containing the count of visits.. and in your flashbanner just call the php file. It'll add one hit per call..
PHP:
<?php
/**
* Create an empty text file called counterlog.txt and
* upload to the same directory as the page you want to
* count hits for.
*
*
* #Flavius Frantz: YOU DONT NEED THESE:
* Add this line of code on your page:
* <?php include "text_file_hit_counter.php"; ?>
*/
// Open the file for reading
$fp = fopen("counterlog.txt", "r");
// Get the existing count
$count = fread($fp, 1024);
// Close the file
fclose($fp);
// Add 1 to the existing count
$count = $count + 1;
// Display the number of hits
// If you don't want to display it, comment out this line
//echo "<p>Page views:" . $count . "</p>";
// Reopen the file and erase the contents
$fp = fopen("counterlog.txt", "w");
// Write the new count to the file
fwrite($fp, $count);
// Close the file
fclose($fp);
?>
Example code from: (google: php counter file) http://www.totallyphp.co.uk/text-file-hit-counter
Code is not tested, but looks ok. I only commented just a little..
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.
So I have a chatroom type of database where the text that a user inserts gets stored into a databse as their username in one field and their message in the other. I want to have my page output the database info, so that people can see each others messages.
How do I do this?
Also, is it possible to make a for loop that checks to see if the database has been updated with a new message, therefore it reloads the page? (Then the page outputs the database info again to update everyones messages)
Please help.. i'm so confused.
Take a look at MySQL functions in PHP manual. You need to connect to the server/database and run a select query to get the data from tables.
As for the loop: you could use JavaScript setInterval function and combine that with AJAX call to periodically poll for new records.
Like the others have said, you will want to connect to your database and then query the table that you have the data in.
while($row = mysql_fetch_assoc($results))
{
echo $row['username'] . " said: " . $row['message'] . "<br />";
}
I use mysql_fetch_assoc() instead of mysql_fetch_array() since the arrays are associative arrays (not indexed by integers, but rather by names (associations))
As for displaying the update on the page dynamically, that involves AJAX. Basically what that means is that your page will call out to a background script to get the new records from the database. This would require a new field in your 'messages' table, something like 'msg_delivered' that you could set to '1' when it has been fetched.
You should check out this if you are interested in making an AJAX chat client: http://htmltimes.com/javascript-chat-client-in-jquery.php
To read anything from a mysql database you would use the mysql_connect() and the mysql_query() functions
eg:
$link = mysql_connect('localhost', 'root', '');
$results = mysql_query('select * from messages');
while($row = mysql_fetch_array($results))
{
echo $row['username'] . ': ' . $row['message'].'<br />';
}
To display new messages the best way would be to use AJAX and poll the database from there, either loading a separate page into a DIV or getting XML back and placing into HTML tags. I would recommend using JQuery for these kinds of tasks. Check http://www.sitepoint.com/article/ajax-jquery/ for an example.