Fetching queries from MySQL and printing it in a javascript calendar - php

I have a hardcoded javascript calendar and I need to print the events from my database which is a PHP MySQL server side database. But I'm not sure how to fetch the queries from mysql and print it into the javascript calendar :/ I found something that makes use of VBSCRIPT but its very confusing :/

The general outline:
Use PHP to access the database and fetch rows of calendar data (using a query). Then, print it out to a Javascript data structure like JSON or native Javascript that is loaded into the browser. Then, work with the Javascript calendar code to load the data into the view the browser presents to the user on the webpage.
There's a lot of variation that can occur here, but roughly (in semi-psuedo code):
Within page contains the calendar (outputs in JSON notation)
<script type="text/javascript">
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_query('SELECT * FROM Events', $link);
$count = 0;
echo "var events = {";
while ($row = mysql_fetch_assoc($result)) {
if ($count !== 0) echo ",";
echo "{";
echo "'eventid':'" . add_slashes($row['eventid']) . "',";
echo "'title':'" . add_slashes($row['title']) . "',";
echo "'description':'" . add_slashes($row['description']) . "',";
echo "'date':'" . add_slashes($row['date']) . "',";
echo "'time':'" . add_slashes($row['time']) . "'";
echo "}";
count++;
}
echo "};";
?>
$calendar = new Calendar(events);
</script>
Of course, there are a number of ways that this could be done, but this is one way it could flow. This is only an example; dropping this code into a PHP page on a server will not work, it's only meant to demonstrate how in general it could flow.

Related

How to create a series of DIVs using PHP + mySQL?

I'm looking to create a formatted product list from an SQL database. My aim is to have a store on my website with a series of small boxes containing some shorthand information about each product, that when clicked will open a pop-up containing detailed information. (I have a working Javascript/JQuery code to create the pop-ups.)
Here is the PHP code so far, simply to get the information from the database and display it on a webpage...
(I've been using XAMPP to provide an environment for me to test the code in)
<?php
mysql_connect("localhost", "root", "") or die (mysql_error ());
mysql_select_db("Database1") or die(mysql_error());
$strSQL = "SELECT * FROM Products";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs)) {
echo $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "<br />";
}
mysql_close();
?>
I want the echoed line to be displayed in a divider, with a divider generated for each record in the SQL database (say I have 10 products available, there would be ten dividers, and 10 different boxes on the webpage). The divider's class is "ProductBox".
echo "<div class=\"ProductBox\">"; $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "</div>";
This was the closest I have come to a solution, which was simply managing to write a code with no syntax errors - alas, nothing actually displays on the webpage.
If I'm going about this entirely the wrong way please tell me - I'm fairly sure I need to use a SQL database to dynamically update stock on a live website, but if I need to implement a different programming language or whatever then just tell me what you think would work and help me with a solution.
You have an extra semicolon in your code
echo "<div class=\"ProductBox\">"; $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "</div>";
Replace with
echo "<div class=\"ProductBox\">". $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "</div>";
mysql_fetch_array needs to be used like this (see PHP Doc):
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
}
or you could just use "mysql_fetch_assoc" instead.
HOWEVER, if you're new to PHP, I HIGHLY RECOMMEND that you get started on the right foot. mysql_query functions are soon to be deprecated. DON'T USE THEM. Most recommend using "PDO" for querying your database. Here's a great tutorial to teach you: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Also, as mentioned, you have an extra semi-colon.
Dont forget these basics markups :
`<HTML>
<HEAD>
</HEAD>
<BODY> put in here your divs
</BODY>
</HTML>`

PHP/MySQL - Unable to INSERT INTO database

I posted a couple days ago and I could not insert an additional record into a MySQL database I setup. I corrected the syntax, but the database will not update again. Basically, I have a couple forms in HTML that carry sessions over to the next pages until the PHP is processes on the final page to INSERT into the database. It worked twice (I have 2 records in the database now), but it won't insert any additional records. It worked fine a couple days ago. The only changes I made to anything was that I added a search feature that accesses the same database with the same user, but the connection is closed at the end of that script as well. Here is the code I am using to INSERT into the database (I know it isn't the best coding job, I'm still learning).
<?php
$con = mysql_connect("localhost","my_username","mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dgibbo1_imaging", $con);
// Here too, please mysql_real_escape_string() all parameters
mysql_query("INSERT INTO imaging (os,MAC,Model,AntiVirus,Browser,Email,Connectivity,Sound,Ports) VALUES ('".$_SESSION['imaging2']."','".$_SESSION['imaging3']."','".$_SESSION['imaging4']."','".$_SESSION['antivirus']."','".$_SESSION['browser']."','".$_SESSION['email']."','".$_SESSION['connectivity']."','".$_SESSION['sound']."','".$_SESSION['ports']."')");
OR die("Could not update: ".mysql_error());
mysql_close($con);
?>
The name of the database is imaging. The columns are setup as:
id (This is the primary key field)
os
MAC
Model
AntiVirus
Browser
Email
Connectivity
Sound
Ports
I just find it odd that it inserted records without any problems until I tried it again today. Is it possible that it has something to do with my code for the search?
The search is a simple form on another page and processes this form:
<?php
$con = mysql_connect("localhost","my_user","mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dgibbo1_imaging", $con);
// Always escape parameters injected into SQL queries
$result = mysql_query( "SELECT * FROM imaging WHERE MAC LIKE '%"
. mysql_real_escape_string ( $search, $con )
. "%'"
);
echo "<table border='1'>
<tr>
<th>MAC</th>
<th>Model</th>
<th>AntiVirus</th>
<th>Email</th>
<th>Browser</th>
<th>Connectivity</th>
<th>Sound</th>
<th>Ports</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['MAC'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['AntiVirus'] . "</td>";
echo "<td>" . $row['Email'] . "</td>";
echo "<td>" . $row['Browser'] . "</td>";
echo "<td>" . $row['Connectivity'] . "</td>";
echo "<td>" . $row['Sound'] . "</td>";
echo "<td>" . $row['Ports'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Meanwhile, the search will pull up the 2 existing records successfully every time, but I can't add new records and I'm wondering if it has something to do with this.
Thanks for any suggestions. I know my syntax probably isn't the best, so any suggestions from this site are always appreciated.
Try creating a separate php file and hard coding the values into it. Run that and see what happens. your search form shouldnt interfere with another form.
edit any errors when using the form? any errors when inserting to another table?
I saw your post, and it all looks "right". What I'd suggest is to add some logging instead of DIE and look at what MySQL is saying about those insert statements:
$sql = "INSERT INTO imaging ....";
mysql_query($sql);
if(mysql_errno()) {
$message = mysql_error() . "\n" . $sql . "\n";
$fp = fopen('c:\mylogifle.txt', 'a');
fwrite($fp, $message);
fclose($fp);
}
AND...as everyone has mentioned, encode those strings - assuming that the SQL is actually being executed, and you "know" it works, there's a very high possibility that some punctuation in one of the values is interfering with the SQL, like an unexpected comma somewhere that confuses MySQL

Help retrieving information from php

I'm building a website where users can view eachother's profile. When a person clicks on another user's name they are directed to their profile page. The URL would look as follows:
http://www.mywebsite.com/profile.php?id=21
In ASP.NET this was trivial to do since I could call controls from C# and edit their text after I've retrieved user information from the database, but i can't seem to find a way how to do the same thing using PHP and jquery. This is how I would like the procedure to go:
User A clicks name of User B
User A is redirected to profile page of User B
Server retrieves information about User B and sends it to jquery
Page is loaded and the HTML fields are filled with the variable contents which were just sent from the server
I guess what i'm finding most hard is how to pass information from php to jquery within the same page.
In PHP you can mix server side code with HTML. You don't really need to involve jQuery to fill the HTML fields (unless you're using AJAX).
You would execute your mysql query and then use that result set to populate the page like so:
This isn't the best code (from w3Schools) but it illustrates the point:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Notice the echo statements. This will output the value from the database into your HTML page.
As I said this is not an example of good code but you can easily change this to add the parameter from the query string (remember to escape the string) to the select statement and output into a profile page.

How to display MySQL data in a list

I will be using data from a MySQL database and to receive that data I will be using this code:
SELECT link, notes FROM links WHERE useri_id=XXX;
I am now stuck on how to display this nicely in a list where it will be a link and then on next line the notes for that link and then a spacer line and then it will display the next link and notes and so on. How would I code this?
You can use something like this:
$rs = mysql_query("SELECT link, notes FROM links WHERE useri_id=XXX") or die(mysql_error());
echo "<ul>";
while( false !== ($row = mysql_fetch_assoc($rs)))
{
echo "<li>";
echo "<a href='" . $row['link'] . "'>" . $row['link'] . "</a><br />";
echo $row['notes'] . "<hr />";
echo "</li>";
}
echo "</ul>";
Use this:
$query = "SELECT link, notes FROM links WHERE useri_id=XXX";
$result = mysqli_query(db_conn_link_var_name, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<ul>";
echo "<li>{$row['link']}</li>";
echo "<li>{$row['notes']}</li>";
echo "</ul>";
}
Coding HTML right in PHP code is not a recommended way.
You should use some templating engine like PHP Smarty or whatever rocks nowadays.
Check e.g. http://devzone.zend.com/article/1238
However, for learning purposes, the other anwsers are just ok.
Ondra's answer is the most reliable one In my view , addition to his answer I suggest you to use PHP frameworks which will take care of many things for you and you can focus on design and code in an organized way.
If you can see all the codes given above are to hard to maintain because of spaghetti nature of PHP coding .
CakePHP and Symfony are really good, Zend needs more time to learn .
But still If you need this code just for a minor database connection use the codes given above.

Google maps v3 - adding php generated markers by user input

Hello i'm trying to make a bus route finder in google maps.
So far i've got a static route to display on the map with the help of google's "Using PHP/MySQL with Google Maps" example.
That works by a php file extracting data from a database and making a xml file, and then the google maps javascript using that xml data to make markers/polyline.
My version: http://www.ykothari.co.uk/gmap-php/gmap-php.html
php code:
<?php
require("dbserverinfo.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect ($dbserver, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM bus109;";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<?xml version="1.0"?>' . "\n";
echo '<markers>' . "\n";
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<markers109 ';
echo 'stopname="' . parseToXML($row['stopname']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'service="' . $row['service'] . '" ';
echo 'stopid="' . $row['stopid'] . '" ';
echo '/>' . "\n";
}
// End XML file
echo '</markers>';
?>
The dataset is like this: https://spreadsheets.google.com/ccc?key=0AqEGwIC84XiqdGZXM2VMS1VPazdrVExsa0t6TjhPWlE&hl=en&authkey=CMSJup8M
Now i want to add a search box for user to type in the bus route number that they want to see, so when they type in say "1" in the search box the php script only gets markers for that routenumber. I assume that the "select * from table" in the php file, is getting the data. Is there a way i can modify this line as the user types it or is there any other way to achieve this? So that the file only fetches the row data for that route and not the entire database as the database about 50,000 entries.
Any links to examples or tutorials are appreciated.
There are a number of steps you'll need to do.
1). Modify your php file to accept GET or POST request parameters with the specific information desired. See this link for more info: http://us.php.net/manual/en/reserved.variables.get.php
2). You'll need to modify the SQL statement:
$query = "SELECT * FROM bus109;";
to include a WHERE clause specific to the structure of your database. http://www.w3schools.com/sql/sql_where.asp
3). You'll need to set the request parameters in your javascript where you make the xmlHttpRequest
downloadUrl('xmlgen.php?bus_route_id=1&....'
...if you choose to use an HTTP Get.
4). Make a searchbox either in a form or with a javascript listener to allow for user input.

Categories