PHP/MySQL Tutorial Thread!

For general discussions of any sort that don't fit in the other forums.

Moderators: Mystic Dragon, Xalia, Shard, JKatkina

Post Reply
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

PHP/MySQL Tutorial Thread!

Post by delyar »

This is mainly so I don't derail other threads with talking about how awesome it is.

1. MAKE SURE YOUR HOST SUPPORTS PHP. This is usually found in your host's FAQ section. Justhost generally does but I'm unsure about other hosts.
2. If you are planning on going the mysql route, you need to have access to that as well. My host provides me with numerous tools for it through my control panel but I prefer phpmyadmin. I am unsure as to how this works if you sublet from a domain.
3. Realize that this takes a really long time to set up depending on how extensive you want your "automation" to be. I have over 550 dragons, so over 550 rows of data, and over 20 columns each. I am still working on filling it all out.

What I use PHP/MySQL for:
- I have all my dragon information in a database.
- Everything you see on pages such as this one is generated through php using data from my database. What this means is that I wrote the code only once and php brings in the information from my mysql database.
- This allows me to build searches that include any field in my database. (I am still working on how to make it search for combinations of fields.)
- PHP can do calculations, such as heat cycles and clutch sizes as seen on pages such as this one. I categorized each dragon by species "type" according to maturity rate, heat cycle length, and average clutch size. PHP then uses this category to perform a sequence of operations to figure out the year of maturity, subsequent years in heat, as well as randomized clutch sizes and amount of duds. (Unfortunately this changes every time I reload the page - I haven't found a way to make it stick.)
- PHP can also hunt down specific lists from my database, as seen by the preferred mate section on the second example page. For that, I told PHP to find dragons within +/- 1 size value.

If you want to just create a search:
- You either need to make a MySQL database or a variable list in php. What you choose is up to you. I have a lot more experience with the database angle but I can figure out how to do the variable list if you want. Information below focuses on the way to do this with MySQL.
- Name your database something you'll remember. Then name your table something descriptive. Mine are "characters" and "dragon_basics".
- In that database, you need to include all the parameters you want to include in your search. I suggest at least Name, Species, Gender, Colour and Home. You likely want to include bond information in the same row (I have mine in a separate database) and the link to that dragon's stats page. See below for example.

Code: Select all

ID#  | DragonName | Species | DragonGender | DragonColour | Origin | BondName | BondSpecies | BondGender | Home | Link
1     | Adharath      | Pernese | Female           | Doom            | ESD     | NULL         | NULL           | NULL           | SULA | statspage.html
MySQL requires a unique column to differentiate between entries. I found it useful to make this column a unique ID#.
- You then write the PHP file:

Code: Select all

<?
//connect to mysql
//change user and password to your mySQL name and password
mysql_connect("localhost","user","password");
//select which database you want to edit
mysql_select_db("characters");
$var = @$_GET['search'] ;
$trimmed = trim($var);

// this is the important part where you edit in the parameters you want to include in your search. use the EXACT names of the columns otherwise your code will give you an error.
$result = mysql_query("SELECT * FROM dragon_basics WHERE DragonName LIKE '%$trimmed%' OR Species LIKE '%$trimmed%' OR DragonGender LIKE '%$trimmed%' OR DragonColour LIKE '%$trimmed%' OR Origin LIKE '%trimmed%' OR Home LIKE '%$trimmed%' ORDER BY DragonName") or die(mysql_error());

// then you type in your page and table structure/headers; echo pretty much means "be seen"; only include the parameters you have included in your database, you won't be able to display that exact info otherwise
echo "<head><title>Character Database: Search</title><link rel=stylesheet type=text/css href=stylesheet.css><center>";
echo "<table><tr><td>Name</td><td>Species</td><td>Colour</td><td>Gender</td><td>Origin</td><td>Bond Name</td><td>Bond Species</td><td>Bond Gender</td><td>Home</td></tr>";

// then you get to start the fun stuff
// this makes your php get the rows that match your search and repeat the following steps until it runs out of rows
// the curly bracket means "within here"; so the repeated steps must be within curly brackets
while($row = mysql_fetch_array( $result )) {

// then you get to start incorporating data into a theoretical row
// this could all go into a single echo, really, but I like to split it up so I know where errors are more easily
echo "<tr><td>";
echo "<a href={$row['Link']}>{$row['DragonName']</a>";
echo "</td><td>";
echo $row['Species'];
echo "</td><td>";
echo $row['DragonColour'];
echo "</td><td>";
echo $row['Gender'];
// and so on and so forth. the syntax is pretty self explanatory and means "express the value for ['COLUMN'] as found in the current row"

// when you're done with your theoretical row, wrap up your repeat clause
	}
// then end your table
echo "</td></tr></table>";

// and that's the end of your php file, save this as search.php

?>
- You then write up the search form - simpler is better. This gets saved as a .html file.

Code: Select all

<b>By Dragon</b><br>
<form name="form" action="search.php" method="get">
  <input type="text" name="search">
  <input type="submit" name="Submit" value="search">
</form>
And that's pretty much it for a search! The hardest/longest part is entering all the data into your database. Some databases can import comma separated value files (.csv) which you can create in excel or openoffice calc - just be careful not to put commas anywhere else or you break them.

Let me know if you implement it and get errors - it's possible that the syntax for the link may cause issues. The most common error is to forget a semi-colon at the end of a phrase. Either way, your file should tell you where the error is (by line number) when you try to run it.

If you want to input something fancy for your unbonded dragons, you can try playing with null values. Null does not mean you just type in "NULL", instead you have to check a box on phpmyadmin to have it be deemed null. Once you do this, you can create an if else clause based on that null as follows:

Code: Select all

if (is_null($row['BondName'])) echo "<td colspan=3>Unbonded</td>";
else echo "<td>{$row['BondName']}</td><td>{$row['BondGender']}</td><td>{$row['BondSpecies']}</td>";
This may seem super confusing but what it does is creates an "override" if you will. If the dragon does not have a bond name in the database, then it will simply say the dragon is unbonded. If it doesn't not have a bond name (ie. it does have a bond name) in the database then it will state the information relevant to the bond. This would go within the repeat in the table section.

Hopefully that's not too confusing! Let me know if you have any questions.
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
User avatar
Dray
Dracolich
Posts: 9389
Joined: Wed Jul 06, 2005 11:16 am

Re: PHP/MySQL Tutorial Thread!

Post by Dray »

Seems thorough and makes sense from a just-reading-through point of view. Looks like my webhost does have MySQL and PHP so I'm all, theoretically, set! :3
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

Awesomeness. :D

I do have ideas for an alternative way of doing the clutch generation stuff if you want to just skip to that in the meantime. Let me know.
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
User avatar
Dray
Dracolich
Posts: 9389
Joined: Wed Jul 06, 2005 11:16 am

Re: PHP/MySQL Tutorial Thread!

Post by Dray »

Tell me more, you know I'm curious. I'm working on a secondary project with Nidus Lacus to see what sort of homogonized dragons I'd get if I allowed a project like the one I'm doing at Corona to run until everything's bred together. X3 But in the meantime, if I could find a way to automate the /drawing/ process that'd be perfect. 9_9 Then again, it's probably better that it's not easily possible, given that dumping images on the Nexus is the last thing I'd want!
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

So this started with just the php code but then I realized i can make it a form instead (see source, save as to get the code of that).

The php file that it loads contains this code:

Code: Select all

<?

// you will have to edit these manually until/unless you incorporate them into your database
// yearb is the year they are born according to your timeline
// speciestype is a designation based on maturity, heat cycle length, clutch size etc
// size is according to nexus guidelines
$yearb = $_POST['yearb'];
$speciestype = $_POST['speciestype'];
$size = $_POST['size'];

// my species types aree as follows
// 1 = typical Pernese etc dragon, 3 years maturity, 3 years heat cycle, clutches 3-15
// 2 = furry dragon, 15 years maturity, 5-6 years heat cycle, litters 1-5
// 3 and 4 were my own species, just ignore those
// 5 = gryphon, 5 years maturity, 8 year heat cycle, litters 1-4
// 6 = Asandae, 40 years maturity, 6-9 year heat cycle, litters 1-3
// 7 = hydra, 3 years maturity, 3 years heat cycle, clutches 5-17
// 8 = winged wolves, 1.5 years maturity, 4-5 years heat cycle, litters 3-7
// 9 = furry dragons, 3 years maturity, 5-6 year heat cycle, litters 4-1

	echo "<table><tr><td colspan=2><b>Extra Info</b></td></tr>";
	echo "<tr><td>Mature In:</td><td>";
	if ($speciestype == 1) $i = ($yearb+3);
	elseif ($speciestype == 2) $i = ($yearb+15);
	elseif ($speciestype == 3) $i = ($yearb+5);
	elseif ($speciestype == 4) $i = ($yearb+15);
	elseif ($speciestype == 5) $i = ($yearb+5);
	elseif ($speciestype == 6) $i = ($yearb+40);
	elseif ($speciestype == 7) $i = ($yearb+3);
	elseif ($speciestype == 8) $i = ($yearb+1.5);
	elseif ($speciestype == 9) $i = ($yearb+3);
	else $i = 0;
	echo $i;
	echo " Y";


	echo "</td></tr><tr><td>Heat Cycle</td><td>";
// here the fun part starts, don't get overwhelmed!
// first we bring in the type of species it is, we're going to deal with Pernese dragons first so...
		if ($speciestype == '1')
			{
// what this next line does is makes this thing repeat until the dragon is too old
// it basically says "beginning with the year of maturity ($i) and continuing until the dragon is 50 years old (year 50 after their birth, so 50+$yearb)"
// the last bit tells the script to leap ahead by 3 years after each loop, which is the duration of the heat cycle
			for ($d=$i; $d<=(50+$yearb); $d=$d+3)
				{
				echo "Year $d: ";
// this next bit is super confusing looking but is quite simple - it gives a 5% (0-5) chance of failing to rise, 5% (5-10) chance of failing to attract a suitor
// and 5% (10-15) chance of rising elsewhere
// the order here is important otherwise the percentages change
					if (rand(1,100)<5) echo "Failed to rise.<br>";
					elseif (rand(1,100)<10) echo "Failed to attract a suitor.<br>";
					elseif (rand(1,100)<15) echo "Rose elsewhere in the Nexus.<br>";
// so if your dragon DOES rise at home, this is what happens
					else {
// again looks confusing but I wanted to be authentic
// small dragons have smaller clutches, so if they're under medium-small, they have clutches 3-7
// and from medium-small to medium-large, clutches are 5-10
// above that, it's 7-15
// again, the order is important
				if ($size<3) echo rand(3, 7);
				elseif ($size<6) echo rand(5, 10);
				else echo rand(7, 15);
				echo " eggs lain";
// and this is the code for duds
// I brought in the size for the first one because small dragons have a lower threshold so they can't have 5 duds but lay 3 eggs
// then I made it so there's a 5% chance of 1-5 duds
// and 10% chance of 1-3 duds
					if ($size<3 AND rand(1,100)>85) {
						echo ", ";
						echo rand(1, 3);
						echo " dud(s)."; }
					elseif (rand(1,100)>95) {
						echo ", ";
						echo rand(1, 5);
						echo " dud(s)."; }
					elseif (rand(1,100)>85) {
						echo ", ";
						echo rand(1, 3);
						echo " dud(s)."; }
					else echo ".";
				echo "<br>";
				 }
				}
			}
// and that's it for speciestype 1 - make sure you don't delete these curly brackets or they break the loop
// using the information above, you can tweak the speciestypes below to your heart's content
		elseif ($speciestype == '2')
			{
			for ($d=$i; $d<=(75+$yearb); $d=$d+(rand(5, 6)))
				{
				echo "Year $d: ";
					if (rand(1,100)<5) echo "Failed to rise.<br>";
					elseif (rand(1,100)<10) echo "Failed to attract a suitor.<br>";
					elseif (rand(1,100)<15) echo "Rose elsewhere in the Nexus.<br>";
					else {
				echo rand(1, 5);
				echo " kit(s) born.<br>"; }
				}
			}
		elseif ($speciestype == '3')
			{
			for ($d=$i; $d<=(50+$yearb); $d=$d+2)
				{
				echo "Year $d: ";
					if (rand(1,100)<5) echo "Failed to rise.<br>";
					elseif (rand(1,100)<10) echo "Failed to attract a suitor.<br>";
					elseif (rand(1,100)<15) echo "Rose elsewhere in the Nexus.<br>";
					else {
				echo rand(4, 7);
				echo " eggs lain";
				if (rand(1,100)>75) {
					echo ", ";
					echo rand(1, 2);
					echo " dud(s)."; }
				else echo ".";
				echo "<br>";
					}
				}
			}
		elseif ($speciestype == '4')
			{
			for ($d=$i; $d<=(150+$yearb); $d=$d+10)
				{
				echo "Year $d: ";
					if (rand(1,100)<5) echo "Failed to rise.<br>";
					elseif (rand(1,100)<10) echo "Failed to attract a suitor.<br>";
					elseif (rand(1,100)<15) echo "Rose elsewhere in the Nexus.<br>";
					else {
				echo rand(1, 4);
				echo " kit(s) born.<br>"; }
				}
			}
		elseif ($speciestype == '5')
			{
			for ($d=$i; $d<=(75+$yearb); $d=$d+8)
				{
				echo "Year $d: ";
					if (rand(1,100)<5) echo "Failed to rise.<br>";
					elseif (rand(1,100)<10) echo "Failed to attract a suitor.<br>";
					elseif (rand(1,100)<15) echo "Rose elsewhere in the Nexus.<br>";
					else {
				echo rand(1, 4);
				echo " kit(s) born";
				if (rand(1,100)>85) {
					echo ", ";
					echo rand(1, 2);
					echo " stillborn."; }
				else echo ".";
				echo "<br>";
					}
				}
			}
		elseif ($speciestype == '6')
			{
			for ($d=$i; $d<=(100+$yearb); $d=$d+(rand(6, 9)))
				{
				echo "Year $d: ";
					if (rand(1,100)<5) echo "Failed to rise.<br>";
					elseif (rand(1,100)<10) echo "Failed to attract a suitor.<br>";
					elseif (rand(1,100)<15) echo "Rose elsewhere in the Nexus.<br>";
					else {
				echo rand(1, 3);
				echo " kit(s) born.<br>";
					}
				}
			}
		elseif ($speciestype == '7')
			{
			for ($d=$i; $d<=(50+$yearb); $d=$d+3)
				{
				echo "Year $d: ";
					if (rand(1,100)<5) echo "Failed to rise.<br>";
					elseif (rand(1,100)<10) echo "Failed to attract a suitor.<br>";
					elseif (rand(1,100)<15) echo "Rose elsewhere in the Nexus.<br>";
					else {
				{
				if ($size<3) echo "5-9 eggs";
				elseif ($size<6) echo "7-12 eggs";
				else echo "9-17 eggs"; }
				echo " eggs lain";
				if (rand(1,100)>85) {
					echo ", ";
					echo rand(1, 5);
					echo " dud(s)."; }
				else echo ".";
				echo "<br>";
					}
				}
			}
		elseif ($speciestype == '8')
			{
			for ($d=$i; $d<=(100+$yearb); $d=$d+(rand(4, 5)))
				{
				echo "Year $d: ";
					if (rand(1,100)<5) echo "Failed to rise.<br>";
					elseif (rand(1,100)<10) echo "Failed to attract a suitor.<br>";
					elseif (rand(1,100)<15) echo "Rose elsewhere in the Nexus.<br>";
					else {
				echo rand(3, 7);
				echo " pups whelped";
				if (rand(1,100)>95) {
					echo ", ";
					echo rand(1, 2);
					echo " stillborn."; }
				else echo ".";
				echo "<br>";
					}
				}
			}
		elseif ($speciestype == '9')
			{
			for ($d=$i; $d<=(45+$yearb); $d=$d+(rand(5, 6)))
				{
				echo "Year $d: ";
					if (rand(1,100)<5) echo "Failed to rise.<br>";
					elseif (rand(1,100)<10) echo "Failed to attract a suitor.<br>";
					elseif (rand(1,100)<15) echo "Rose elsewhere in the Nexus.<br>";
					else {
				echo rand(4, 10);
				echo " eggs lain";
				if (rand(1,100)>85) {
					echo ", ";
					echo rand(1, 2);
					echo " dud(s)."; }
				else echo ".";
				echo "<br>";
					}
				}
			}
		else echo "Sterile";

		if ($speciestype == 7) echo "<br>Some offspring may be 'evil'.";


		echo "</td></tr><tr><td>Gestation Time:</td><td>";
		if ($speciestype == 1) echo "10 Months";
		elseif ($speciestype == 2) echo "6-10 Months";
		elseif ($speciestype == 3) echo "7 Months";
		elseif ($speciestype == 4) echo "12 Months";
		elseif ($speciestype == 5) echo "10-12 Months";
		elseif ($speciestype == 6) echo "6 Months";
		elseif ($speciestype == 7) echo "6-10 Months";
		elseif ($speciestype == 8) echo "5-6 Months";
		elseif ($speciestype == 9) echo "10 Months";
		echo "</td></tr><tr><td>Offspring Require Bond:</td><td>";
		if ($speciestype == 1) echo "No, but greatly preferred";
		elseif ($speciestype == 2) echo "No";
		elseif ($speciestype == 3) echo "Yes, no exceptions";
		elseif ($speciestype == 4) echo "No";
		elseif ($speciestype == 5) echo "No";
		elseif ($speciestype == 6) echo "No";
		elseif ($speciestype == 7) echo "No";
		elseif ($speciestype == 8) echo "No";
		elseif ($speciestype == 9) echo "No, but preferred";
		echo "</td></tr></table>";
?>
Unfortunately I can't bring in a list of potential suitors without giving them all a size variable at the beginning which would be crazy tedious and is so much easier with a database.
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
JKatkina
Ancient Dragon
Posts: 2418
Joined: Wed Jul 06, 2005 12:37 pm
Location: Canadia
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by JKatkina »

This is fascinating... I'm trying to figure out how to implement it to generate pages. I have a couple of questions in that regard.

If I have a thumbnail for my dragon or character, and I want to include it in a table-list of characters, can I do that in the MySQL database? Like add a 'Thumbnail' column and put in dragon.jpg? (actually I just looked at your characters-new page and it looks like you did just that! :o )

You say you have separate databases for bonds and dragons. How does that work out?

Also for that matter, how do you implement page generation? Is there a PHP file that generates dragon pages? I checked out your characters-new database, and it looks like there's a template.php file that generates a page for each ID number? That suggests you could have a number of template files... which puts forth interesting possibilities. Could you mess with the template files so that you define a background image for each character or dragon, and import that on the page?

Can you have more than one value in a column? Like if I had "Abilities" as the column title, could I like... put multiple entries in each dragon's ability column? Do you know what I'm trying to ask? XD

Uh, I'm sure there'll be others as I go. This looks keen!
Image Image Image Image
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

Thumbnails: Yes that's exactly what I did. I have a field in the database for thumbnail, where I put the image name. (I have all my thumbnails in a single folder.) The same works for images.

Two databases:It's pretty simple - I just have to "call" the information from both databases. So like "select * from dragon_basics where dragonID == $id" and "select * from bond_basics where dragonID == $id". You can do this for a ridiculous amount of databases and I think it affects your page load time or bandwidth very slightly but it's fairly easy. It's not much different from calling up information for two rows in a single database. Does that make sense?

Template files and background images: You could have a number of template files, you'd just have to specify which you want for which character some place in the database. However, doing the background image is very simple and is akin to importing the character image at the top of the page. You just specify it in the database (or some kind of marker for which image you want) and then code for it. For example, you could have a thing like "background" and have numbered values for which background using an if clause (ie. "if (background == '1') echo "<body background=image1.gif>"; elseif (background == '2') echo "<body background=image2.gif";" etc.)

Multiple values in one column: I think in theory but I haven't bothered to mess with that as that makes an array within an array, which can be tricky. You can make it into a text box which lets you input X characters and just lop them all in but it wouldn't recognize them as separate. What I have is I think... 15-20 Ability columns. It was simpler at the time.

If you want me to post my template.php file just let me know. :)
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
JKatkina
Ancient Dragon
Posts: 2418
Joined: Wed Jul 06, 2005 12:37 pm
Location: Canadia
Contact:

Post by JKatkina »

I would looove to see your template.php file. This is literally the first day I've dabbled in this stuff, I feel totally in the woods. Actually I'm not entirely clear on the very basics, although I think I'm getting the theory of how it all fits together. How does one even make a .php file? Is it just the same kinda thing as HTML, put in the appropriate code and save it as a .php or is it some sort of backend shenanigans like I'm having to get into the make a mySQL database here?

Re: templates, the idea I had (aside from having more than one shiny way of displaying my dagrons) was to have one template for unbonded characters, and one for bonded characters -- so one would only have one stats table and the other would have two. Is there a way to do that? If I'm defining IN the database what template I want for what character, is it possible then to have two characters with distinct entries appear on the same page?

The background thing I'm not 100% following. What I'd like to do is be able to have each character have a distinct background. Would that be best accomplished by defining background numbers that correspond with the character's ID#, or by inputting a filename into the character's table and then putting it in the code as (forgive me if I muck this, I don't have the syntax down yet):

echo "<body background="";
echo $row['Background'];
echo "">";

Where "Background" would be something like "/bgs/charbg.gif"?
Image Image Image Image
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

To make a PHP file: You have to save it as .php for your server to recognize that you are using the language for PHP. That's all the requirements, really.

Templates: Yes, you could do that. It could a be a giant if clause (ie. if (isset($row['BondID'])) { "huge amount of code here" };)) to bring in the second chunk of information or you could specify two templates and manually change them within the mySQL database.

Background: Easier your way. Though you could even change it to:

echo "<body background=/bgs/";
echo $row['Background'];
echo ">";

I wasn't sure if you were doing unique or categorized. (My way works better for, say, all people living in Place A have Background A etc.)

Here's my file saved as a .txt: http://lambeosaurine.com/characters-new/d-template.txt
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
User avatar
Dray
Dracolich
Posts: 9389
Joined: Wed Jul 06, 2005 11:16 am

Re: PHP/MySQL Tutorial Thread!

Post by Dray »

Ow, my brain hurts. XD How much do I have to pay someone for building one of these things for me? :P
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

More than I was willing to pay. :P I find it less confusing and more tedious over time but it definitely still leads to me thinking in PHP syntax for the rest of the day.
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
User avatar
StarFyre
Ancient Dragon
Posts: 3246
Joined: Wed Jul 06, 2005 10:44 am
Location: Middle of Nowhere
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by StarFyre »

0.o Huh. Interesting take on building a page. In comparison, here's my template to build an index page (in this case, the Vecira index page: http://www.silveredmagic.com/candis/cla ... index.html ): http://silveredmagic.com/test/veciraindex.txt

I will note that it's the same theory, but gone about in a different manner - whereas Delyar's posting everything directly to the page immediately, I'm saving things in variables and posting it at the bottom, and then saving it to a page in another part on the site. I am halfway tempted to create another couple tables and put all my info into it, to allow a cronjob to build all my pages as it desires, but that means transferring over over 300 pages, plus stories, so... nah.

ALSO, on that note - Dray, I finished the code for the breeding php. Or, at least, I BELIEVE I have done so, as I don't seem to be running into any more infinite loops or issues. Feel free to ask questions - I think I commented it clearly enough, but, er, I'm a programmer, so what I consider "clear" may not actually be clear to a newbie. Included in the zip is a copy of the table that I built to go along with the php - all you need to go is go into phpmyadmin, create a database, then import the .sql file that's in the zip and it'll build an empty table for you to start loading with dragons =P Have fun! http://nexusdragons.com/testing/draybreeding.zip
User avatar
StarFyre
Ancient Dragon
Posts: 3246
Joined: Wed Jul 06, 2005 10:44 am
Location: Middle of Nowhere
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by StarFyre »

delyar wrote: Multiple values in one column: I think in theory but I haven't bothered to mess with that as that makes an array within an array, which can be tricky. You can make it into a text box which lets you input X characters and just lop them all in but it wouldn't recognize them as separate. What I have is I think... 15-20 Ability columns. It was simpler at the time.
Doublepost because I can (and I'm finally reading through all this). Multiple values in one text column are easy enough to deal with if you separate them with a deliminator (such as , or - or &... y'know, something that won't show up inside your data). At that point, you go

Code: Select all

$abilities = explode('& ', $abillist);
$acount = count($abilities);

$newlist = "<ul>";

for($i = 0; $i < $acount; $i++){
   $newlist .= "<li>$abilities[$i]</li>";
}

$newlist .= "</ul>";

The above assumes that the deliminator is &, and that you want to make a list out of it. If all you want is your "Telepathy, Teleportation, Firebreath" sort of thing, just text-box that and drop it in place. Or, fury, you can just put straight html into the text-boxes, I believe. In which case, just write what you want to show up. =P I like text-boxes. They are my god.
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

Glad to have someone who knows what they're doing pop in here. :) My method/code isn't the cleanest, especially since I'm building it from the ground up in a way that I understand. I'm also constantly updating and changing it as I learn more efficient ways of asking for things.
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
User avatar
StarFyre
Ancient Dragon
Posts: 3246
Joined: Wed Jul 06, 2005 10:44 am
Location: Middle of Nowhere
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by StarFyre »

My code is hardly what you'd call clean either =P It's just that I've had years more to explore coding (and thus I've already stepped directly through the stage you're at and have moved on from there), and thus know more tricks.

Let's see what else I can attempt to clear up or expand upon...

This: http://silveredmagic.com/test/search.txt is the backend to my search, which allows for multiple things to be selected for at once. It's really just a matter of building the SQL statement properly, which you can have fun exploring in phpmyadmin in the SQL tab.

If you want to get the heat-cycle calculations to stick, make another field in the table and do something like this:

Code: Select all

if isset(heatcycle box)
   just print it out
else
   build the heat cycle data, save it into a variable such as $cycle then update the database
   $sql = "UPDATE dragontable SET heatcycle=$cycle WHERE DragonID=$id"
That'll make sure that it's stable.

Two databases - I think you're confusing tables and databases, but the answer is yes either way. Tables are the different collections of data in a single database (Example: I have a database called Dragonbase that has three tables - Dragons, Riders, and Wilds. I have two databases on that same server - Dragonbase and Timelines.) If you want access two distinct databases you have to set up two distinct connections. Tables, however, only require one connection and are easily accessed and switched between.

Code: Select all

Accessing two different databases:

$dbname = "silver13_dragonbase";
$dbname2 = "silver13_timelines";

$dbh1 = mysql_connect("localhost", "username", "password") or
    die("Could not connect: " . mysql_error());
$dbh2 = mysql_connect("localhost", "username", "password", true) or
    die("Could not connect: " . mysql_error());

mysql_select_db($dbname, $dbh1);
mysql_select_db($dbname2, $dbh2);

Then grabbing information from a table inside one of those databases:

$sql = "SELECT * FROM myrsilk";
$result = mysql_query($sql, $dbh2);

$sql = "SELECT * FROM Dragons";
$result = mysql_query($sql, $dbh1);

Accessing two different tables:

$sql = "SELECT * FROM table1";
$sql2 = "SELECT * FROM table2";
Do note that collating two different databases is very resource heavy, and not suggested for dynamic pages. Two different tables, on the other hand, is rather common and not as resource heavy.

My inner engineer cringes at the fact that you have dynamically written pages that rebuild every time I click on a page - if you have a lot of traffic or a large page to build, that could quickly lead to heavy lag. On the other hand, it's your server and your pages, so I'm not going to grawr at you much =P
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

Heat cycles: I'm not sure I understand what you mean here, probably because the code looks incomplete to me. I assume what you're writing would generate the years the dragon went into heat and then save them into the database so it would require a loop of some sort, right?

Durr, I knew that about tables and databases but managed to confuse them, you're correct. I am running two tables within a database. I don't have another database, so I frequently confuse the two terms. Sorry about that!

In regards to your last paragraph: What would you suggest as an alternative to what I have going right now? I find working with mysql to be a lot less effort than typing up individual html pages... but I'm assuming there's something in between what I have now and what I had before.
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

And sorry for the double post, but could you link your functional search page again? I'm trying to wrap my mind around the code and tend to work better if I can input stuff and check what it does.

EDIT: Durr, found it but going to link it here for easy finding if someone tries to use this thread later: http://www.silveredmagic.com/candis/search.html

Seeing the format of your search page makes that code make a LOT more sense. I was boggled by trying to figure out how a simple text input could turn into that.
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
User avatar
StarFyre
Ancient Dragon
Posts: 3246
Joined: Wed Jul 06, 2005 10:44 am
Location: Middle of Nowhere
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by StarFyre »

Sorry - the heatcycles code is what's called psuedocode. I don't know all of your math in order to actually write the real code, so instead wrote an outline of what needs to be put where. And yes, it would generate the years and then save it into database. The "If-else" is there to check to see if there's something in the database already for that, and if there isn't, only then does it generate the years.

Tables VS Databases - I figured as much, but wanted to clear that up, in case someone actually has use for accessing multiple databases at once. It took me a bit of find that bit of code when I was searching for it.

I'd suggest saving them as static pages. You can see a partial example of what I mean by that at the very top and very bottom of the veciraindex.txt file, with the fopen and fwrite and fclose, though. fopen is here: http://php.net/manual/en/function.fopen.php And you can find the rest (along with other useful file operators) on the list to the left. As said though, it's up to you (and I'm mostly stating it because, in a way, creating static pages is one of the next steps in learning php website creation)

EDIT: Er, wow, I didn't link the search page? I thought I had. Sorry about that! ^^;; And yeah, it tends to be rather complicated, since I'm doing a rather huge cross-field search. On the other hand, the search page is really just a bunch of smaller segments that are built individually and then put together at the end.

EDITREDUX: For your edification, I have uncommented the echo $sql statement in the search.php. So now, if you go to search.html and run a search query, it will output what the actual sql query is that's being passed to the server.
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

I'm going to dumb this down extremely so I apologize in advance for the brainhurty that may come from it. So basically a static page is a public version of a cached page, right? Like, when you're working offline and it's like "hey, I can't connect to that page but I can load a cached page!" except not saved on a computer but on a server, right?
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
User avatar
StarFyre
Ancient Dragon
Posts: 3246
Joined: Wed Jul 06, 2005 10:44 am
Location: Middle of Nowhere
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by StarFyre »

A static page is a page that just... exists. This is a static page: http://www.silveredmagic.com/candis/yikaeri.html It is not rebuilt on load and it constantly exists on the server in that exact state. A dynamic page, on the other hand, is like your templated pages - every time I load that page, I'm directly asking your database to show me what it contains.
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

Okay. I think I understand that. And writing the code once will save multiple pages, right?

Tangentially, did you use an include to bring in multiple locations/allegiances to the same index page?

I'm also confused as to how you brought in the titles. I see that you specified an array of what they mean but I fail to see what input you're "converting" (for lack of a better term) to it. The only thing that makes sense is if you put a number in your Position column, is that right?

Sorry if these questions are annoying/ridiculously basic. It's really hard to go through someone's code and understand what is going on!
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
User avatar
StarFyre
Ancient Dragon
Posts: 3246
Joined: Wed Jul 06, 2005 10:44 am
Location: Middle of Nowhere
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by StarFyre »

delyar wrote:Okay. I think I understand that. And writing the code once will save multiple pages, right?
Theoretically, if you design the template.php page and the corresponding database table correctly, you could use one template.php page to create multiple different appearances.
delyar wrote:Tangentially, did you use an include to bring in multiple locations/allegiances to the same index page?
As in how it is here: http://www.silveredmagic.com/candis/index.html where Akelara, Vecira, the Devyrs, etc are all listed on the same page? If that's what you're asking, what I have is a column in my table that's labeled Allegiance which is an ENUM set. Here's the actual code for the index.html page http://www.silveredmagic.com/test/indexcreation.txt
delyar wrote:I'm also confused as to how you brought in the titles. I see that you specified an array of what they mean but I fail to see what input you're "converting" (for lack of a better term) to it. The only thing that makes sense is if you put a number in your Position column, is that right?
Actually, my Position column is a text box where I enter what position I want the dragon/rider to be in. "Clan Member" "Warrior" etc. The array of titles that you see is there so that the dragons that are outputted are put in a specific order that I have designated. So, if the results that I've pulled from the table go "Warrior, Warrior, Healer, Warrior, Clan Member, Leader, Leader, Clan Member" I would search through, find the Leaders, then the Warriors, then the Healers, then the Clan Members. Of course, that's a bit simplistic, but that's the general idea of what's happening.
delyar wrote:Sorry if these questions are annoying/ridiculously basic. It's really hard to go through someone's code and understand what is going on!
Delyar, learning comes through asking questions. If I wasn't interested in trying to explain my terrifying mental pathing that I take to create these php pages, I wouldn't have shown them off =P There are no stupid questions, especially in something like this - you're trying to learn a new language and a new way of thinking. All I ask is that you hit me over the head if I basically go over your head with my explanations. Do remember, I've been doing this for years, so things that seem "obvious" to me may be completely unclear to you.
User avatar
StarFyre
Ancient Dragon
Posts: 3246
Joined: Wed Jul 06, 2005 10:44 am
Location: Middle of Nowhere
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by StarFyre »

Er, doubleposting to clear up something on the multiple allegiances on a single page - When I'm pulling the information from the table, I'm actually pulling the entire table and THEN sorting through it with the help of a Switch statement to find the allegiances that I want to show on that page. No real fancy sql calls involved ^^;;
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

Makes sense. :) Thanks for clearing that up. I'm sure I'll have more questions later!
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
User avatar
StarFyre
Ancient Dragon
Posts: 3246
Joined: Wed Jul 06, 2005 10:44 am
Location: Middle of Nowhere
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by StarFyre »

Cheers ^^ Hopefully I'm helping you learn, and not just shoving my way of doing things down your throat.
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

Oh it's totally helping! I just have a lot of "why" questions that I can't properly parse at 1 AM so I'll mull them over a bit and try stuff before asking them. It's always nice to have another perspective, especially when I'm not set in my ways yet.
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
User avatar
StarFyre
Ancient Dragon
Posts: 3246
Joined: Wed Jul 06, 2005 10:44 am
Location: Middle of Nowhere
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by StarFyre »

Oh good ^^ Yeah, some of my incoherency and ramblings might be the result of the fact that it's midnight, I'm watching TV, AND my cat is being adorable and playing with a live mouse that he found.
delyar
Dragon
Posts: 732
Joined: Wed Jul 06, 2005 12:08 pm
Location: Ottawa, Ontario
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by delyar »

Ok Star, another question for you because I'm legit stumped.

I'm trying to do a two-column query and then make a while loop for it, similar to what I use for my search page tables. However, for some reason, this isn't picking up on half the entries that apply! I've checked and rechecked my format on those entries and they are identical to the entries that DO show up. I have no idea what is causing this, so I think it might be something simple that I've missed due to inexperience. (Or because I have over 1000 rows of data in this table. Can they break if they get too big?)

This is the relevant bit of code (and here is a page with it somewhat working):

Code: Select all

$kid = mysql_query("SELECT * FROM dragon_pedigrees WHERE (MID='$id' OR FID='$id') ORDER BY YearH");
$kids = mysql_fetch_array($kid);

	if ($row['DragonGender']='female') {
		if (isset($kids['FID'])) echo "<a href=d-template.php?id=" . urlencode( $kids['FID'] ) . ">";
		if (isset($kids['F'])) echo "{$kids['F']}</a>";
		if (isset($kids['FS'])) echo "<br>{$kids['FS']}"; }
	else {
		if (isset($kids['MID'])) echo "<a href=d-template.php?id=" . urlencode( $kids['MID'] ) . ">";
		if (isset($kids['M'])) echo "{$kids['M']}</a>";
		if (isset($kids['MS'])) echo "<br>{$kids['MS']}"; }
	if (isset($kids['OfficialN'])) echo "<br>{$kids['OfficialN']} @ {$kids['Location']}";
	if (isset($kids['YearH'])) echo "  in DY {$kids['YearH']}";
F = Father, M = Mother
Furthermore, I'm having my males list themselves as their own mates (even if they pull the right clutch) which I can't seem to fix.

Any insight? I apologize for my patchwork code hurting your eyes/brain in advance!
Character Listing
Site Listing - Links to All Sites (Link back here if confused!)
User avatar
StarFyre
Ancient Dragon
Posts: 3246
Joined: Wed Jul 06, 2005 10:44 am
Location: Middle of Nowhere
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by StarFyre »

Posting a note to say I've seen this and will look into it in depth in the next few hours - I have class soon, and there's no internet there =P
User avatar
StarFyre
Ancient Dragon
Posts: 3246
Joined: Wed Jul 06, 2005 10:44 am
Location: Middle of Nowhere
Contact:

Re: PHP/MySQL Tutorial Thread!

Post by StarFyre »

As far as I know, length of a table shouldn't matter in whether or not a result shows up, only in how long a query takes. One thing to test if it's not being pulled by the query, or if it just isn't showing up period is to do print_r($kids) and see what's spit out (it might take a moment to understand the mess that print_r spits out, but it's generally a good test). It looks like the most problem comes from the males? Are all the problems just on the male side of things, or do some of the females pages have the same issues? Also, what's your loop look like? If I'm not entirely mistaken, the code you posted looks like the code for just the mate/time/place, unless I'm reading it wrong? Can I see the full php, as there doesn't seem to by anything syntactically wrong in what you posted in the slightest.
Post Reply