Loading JavaScript Arrays with MySQL Data 1st edition by Alex Ressi pdf download
Loading JavaScript Arrays with MySQL Data 1st edition by Alex Ressi pdf download
_____ Follow the link below to get your download now _____
https://ebookball.com/product/loading-javascript-arrays-
with-mysql-data-1st-edition-by-alex-ressi-14054/
https://ebookball.com/product/client-server-web-apps-with-javascript-
and-java-1st-edition-by-casimir-
saternos-1449369316-9781449369316-20258/
https://ebookball.com/product/dna-arrays-technologies-and-
experimental-strategies-1st-edition-by-elena-grigorenko-
isbn-9781420038859-1420038850-9724/
https://ebookball.com/product/analyzing-business-data-with-excel-1st-
edition-by-gerald-knight-9780596553463-0596553463-12548/
Loading JavaScript Arrays with MySQL Data
By Alex Ressi
All materials Copyright © 1997−2002 Developer Shed, Inc. except where otherwise noted.
Loading JavaScript Arrays with MySQL Data
Table of Contents
Introduction &Explaination..............................................................................................................................1
Source Reference.................................................................................................................................................6
i
Introduction &Explaination
We have all seen pages that use JavaScript for better or for worse. In many cases JavaScript can improve a
site's functionality and ease of use. Unfortunately administrating some of the complicated arrays that
JavaScript depends on for things like heirarchichal menus and dynamic forms can be a pain in the rear. That's
why were going to turn the task over to PHP and MySQL. We can use this combination to load data into the
JavaScript for us. This is particularly useful if information contained in the array is likely to change.
In this exercise we will build a selection component for a resource management system. The component will
tie people and project together based on staffing needs and employee skill. It will also illustrate how PHP and
MySQL can be used to dynamically build JavaScript. The static component code is below.
Use the drop down menu below to select the skills required for the
project. The list of personnel will change according to skill. Use the
arrows arrows to control the addition or subtraction or people to the
project.
This component uses two popular JavaScripts which are readily avialable on the web. I grabbed the JavaScript
for the 'menu swapper' from www.javascriptsource.com, and I picked up a script to handle the drop down
menu change from www.webreference.com.. With a little time, I managed to get the two scripts to work
together as planned. View the source to see the resulting code. One of the first things you will notice is the
following JavaScript array.
The above code will serve as a model while we write our PHP code. Let's take a quick look at the anatomy of
an array. The first set of brackets, ar[x], in this multi−dimentional array refers to the skill. The second set of
brackets ar[x][x] is the array index of the item, which will always begin by default with 0. The item in this
case is the employee. This array will be replaced by PHP code which will dynamcally build it. Now that we
have played around with the component and had a look at the source code, it would be a good idea to build
and populate that database.
Once the database has been built and populated, we need to do the following things to make our JavaScript
dynamic. Note: The only portion of the source code that will be dynamic is the array, the rest of the JavaScript
will remain static.
1. The database needs to be queried for employee names, and employee skills (two separate tables). The
results need to be ordered by skill.
2. We will then need to loop through the skills printing the employee names associated with the skill
3. A mechanism then needs to be built to pass the employee id, skill id and project id to the form
processing component.
Let's begin with the query. Have a look at the database schema to see how the information is stored. There are
3 tables involved in this component. Personnel, Skill, and person_skill.
$sql = "SELECT
p.person_id,
s.person_id,
CONCAT(last_name,', ',first_name) AS name,
skill_id";
$sql .= "FROM
personnel p,
person_skill s
WHERE
p.person_id = s.person_id
ORDER BY
skill_id, name";
$result = mysql_query($sql);
The SQL statement is pretty straightforward. If you are unsure about what is going on here, you can always go
to the MySQL site where there are numerous tutorials. The important thing to note in this query is the
ORDER BY clause, which will properly setup the arrangement of the resulting data. After performing our
SQL we then initialize two variables:
$type = "";
$number2 = "0";
We then will perform the while loop which will actually build the JavaScript array.
A series of "If then" statements will control the proper formation of the array.
if ($myrow[3] != $type) {
The first if statement checks to see if the variable $myrow[3] which is the skill_id from our SQL statement, is
NOT equal to the variable $type. $type was set outside of the loop to nothing. The two values are not equal, so
the next expression will be evaluated.
if ($number2 != NULL) {
We have a new variable to start with, $newnumber2 which is given a value of 1. (0 + 1 = 1) The first line of
the JavaScript array is then printed. ar[0] = new Array();
$number2 which was initially set to 0, now takes on the value of $newnumber2 which is 1. $type now is given
a value. Initally set with no value and now $type has the value of $myrow[3] which is 0.
From this code block we get the first part of the next line, namely ar[0][0]. The first '[0]' refers to the skill, so
it will be repeated for each person that is associated with that particular skill. The next '[0]' refers to an
individual possessing the skill. There is an "if statement." that increments the number in the second set of
square brackets for each row in the database.
Before closing the while loop, we are going to append "= new makeOption("Crown, Tom", "151");" to the
"ar[0][0]", thus completing one pass through the loop. The loop will be run for each row in the database
query, which is in this case is 21. You can view the entire unbroken source code here. The next challenge will
be passing multiple values to the form processing script. This will be done using a combination of JavaScript
and PHP, and will be the focus of a seperate upcoming article.
In addition to building JavaScript arrays, this code can be hacked up for a number of other uses . What this
Plug this in place of the JavaScript array in the source code of the refering page and go! PHP can be inbeded
in JavaScript tags.
<?php
$db = mysql_connect("localhost", "root", "");
// This establishes a link to MySQL
mysql_select_db("extranet",$db); // The database is specified
$sql = "SELECT
p.person_id,
s.person_id,
CONCAT(last_name,', ',first_name) AS name,
skill_id ";
$sql .= "FROM
personnel p,
person_skill s
WHERE
p.person_id = s.person_id
ORDER BY
skill_id, name";
$result = mysql_query($sql);
$type = "";
$number2 = "0";
while ($myrow = mysql_fetch_row($result)) {
if ($myrow[3] != $type) {
if ($number2 != NULL) {
$newnumber2 = ($number2 + "1");
print ("ar[$number2] = new Array();\n");
$number2 = $newnumber2;
$type = $myrow[3];
$number = "0";
}
}
print "ar[" . ($number2 − "1") . "]";
if ($number != NULL) {
$newnumber = ($number + "1");
print ("[$number]");
$number = $newnumber;
}
print (" = new makeOption(\"$myrow[2]\",
\"$myrow[1]$myrow[3]\");\n");
Source Reference 6
Loading JavaScript Arrays with MySQL Data
}
?>
The drop down menu with skills is also database driven so that new skills can easily be added to the database.
Here is the code that was used to generate it.
$sql2 .= "FROM
skill s,
person_skill p
WHERE
s.skill_id = p.skill_id
ORDER BY
s.skill_id";
$result2 = mysql_query($sql2);
The following is the code to build and populate the the tables that are used in this module. It can be cut out of
the web page and then pasted into a text file on your database server where it can then be imported by MySQL
using the mysqlimport command.
#
# Table structure for table 'personnel'
#
CREATE TABLE personnel (
person_id int(11) DEFAULT '0' NOT NULL auto_increment,
first_name varchar(15),
last_name varchar(15),
company varchar(30),
PRIMARY KEY (person_id)
);
Source Reference 7
Loading JavaScript Arrays with MySQL Data
# Dumping data for table 'personnel'
#
#
# Table structure for table 'person_skill'
#
CREATE TABLE person_skill (
person_id int(11) DEFAULT '0' NOT NULL,
skill_id tinyint(2),
level tinyint(1)
);
#
# Dumping data for table 'person_skill'
#
Source Reference 8
Loading JavaScript Arrays with MySQL Data
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (27,3,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (30,6,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (32,1,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (32,2,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (34,1,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (34,2,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (34,7,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (36,1,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (36,2,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (42,1,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (42,2,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (42,7,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (43,4,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (43,2,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (43,3,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (44,2,NULL);
INSERT INTO person_skill (person_id, skill_id, level)
VALUES (44,3,NULL);
#
# Table structure for table 'skill'
#
CREATE TABLE skill (
skill_id int(11) DEFAULT '0' NOT NULL auto_increment,
skill_name varchar(20),
skill_desc varchar(250),
PRIMARY KEY (skill_id)
);
#
# Dumping data for table 'skill'
#
Source Reference 9
Loading JavaScript Arrays with MySQL Data
INSERT INTO skill (skill_id, skill_name, skill_desc)
VALUES (6,'Oracle',NULL);
INSERT INTO skill (skill_id, skill_name, skill_desc)
VALUES (5,'ASP',NULL);
INSERT INTO skill (skill_id, skill_name, skill_desc)
VALUES (4,'Cold Fusion',NULL);
INSERT INTO skill (skill_id, skill_name, skill_desc)
VALUES (3,'Vignette',NULL);
INSERT INTO skill (skill_id, skill_name, skill_desc)
VALUES (2,'JavaScript',NULL);
INSERT INTO skill (skill_id, skill_name, skill_desc)
VALUES (1,'HTML',NULL);
INSERT INTO skill (skill_id, skill_name, skill_desc)
VALUES (7,'MySQL',NULL);
Source Reference 10
Other documents randomly have
different content
The Project Gutenberg eBook of Vassals of the
Lode-Star
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.
Language: English
The purple light came first, tinting the library of the old house, and
flooding across rugs and books on the shelves. Then the mansion
rocked and tilted as though being lifted and torn loose from its
foundation.
Thor Masterson came up from his chair, brown eyes staring. His
flannel shirt opened to disclose tanned chest and thick neck. He saw
the purple light, but he did not think of it as a pathway between
worlds. He felt the tilting of the house, but he did not think of it as
riding down the cosmic corridor through which it was being
transported.
The mansion rocked and turned slowly. If Thor could have had time,
he might have tried to reason, but there was no time—
A woman stood in the center of the rug, a woman with long yellow
hair and gauze trousers and jeweled girdle. A dwarf-man with a big
club leaped for her, snarling. The woman whirled, a slim dagger
glittering in her right hand.
Thor Masterson came alive. He drove forward. His big right fist,
scarred with battles in Oregon lumber camps and wise to the ways
of axes and bounding footballs and enemy jaws, swept up in a short
arc.
The dwarf-man seemed to leap backward. He fell against an antique
secretary, splintering wood. Slumping toward the floor, he lay still.
The girl screamed.
Again the mansion was rocking and tilting, lifting and falling. A chair
skidded into a corner, and a heavy picture dropped with a shattering
of glass and frame.
Thor Masterson thought of hurricanes and cyclones and tidal waves.
He held the girl against him, looking into her frightened violet eyes.
"Easy does it. Just take it easy. Relax. It's like skiing. If you're not
stiff, you won't get broken bones."
The violet eyes told Thor that she hadn't the slightest conception of
what he said, but his tones made her generous red mouth yield a
tremulous smile. She relaxed and lay against him.
Thor stared out the window. There should be the elms of the
Midwestern campus out there, but all he could see were pale purple
mists. Thor went toward the window and peered out. Midwestern
University, where Thor had come from lumber camp and battlefield,
ought to be showing its greystone buildings soon. But the more Thor
stared into the lavender mists, the colder became his heart.
Because, as the clouds shifted to reveal darker spaces, Thor could
see stars glittering in the blackness. He thought, Something has
lifted the house right off the campus. Something has us in its grip.
We're being taken away from the Earth—taken out in space. For he
knew from the star formations that he could see momentarily, that
something was moving him and the house swiftly across the void.
The house bumped, pitching at a gentle angle. The floor was like the
deck of a ship caught in the trough of a wave. Thor rolled with it,
legs straddled.
The front door cracked open as the house settled onto something
solid. The purple mists began to flee before the pale yellow light
streaming through the door and window.
Thor walked with the girl to the doorway and stood on the cracked
sill, looking out. I'm delirious, he thought. I've read some fantastic
tale and gotten drunk, and this is the result. What I'm looking at is
the chaos of a surrealist nightmare.
Sprawling grey rock humped itself into impossible contortions under
the warmth of a great yellow sun. Where the rock disappeared, red
grass swayed its blades. Low mists hung in the distance.
The girl whimpered. She whispered in a language that made Thor
think of jewels in a tumbling spring, clicking and clacking. He
grinned down at her.
"Don't ask me, sweet stuff," he said. "Offhand I'd say that Dali had
us in one of his landscapes. And you wouldn't know about him. But
as far as any explanation of where we are or what happened, I'm up
a tree. Still, I rather imagine that something went wrong with the
space coordinates."
He went on dreamily, "We don't know an awful lot about space.
Maybe it moves along with the rest of the expanding universe, and
maybe it doesn't. But if a certain segment of space was addicted to
going off on a tangent—away from its usual sphere—it could
conceivably snatch up whatever was in its path, and sort of kidnap
it. Get it, sweet stuff?"
Like a woman, she ignored everything but the one thing. Seriously
she repeated, "Sweet stoff. Sweet stoff."
Thor laughed, "That's you." He touched her with his finger. She
shook her head vigorously, making the yellow hair fly out fanwise.
"Karola, Karola," she said insistently.
"Karola. Okay. I'm Thor."
The violet eyes were sliding over him, taking in his big frame and
long legs. Thor flushed a little, reading the frank admiration in her
eyes. Felling logs and playing an all-Conference grade of tackle on
the football team had built up an already good physique. But the
years of logging and football and fighting had left little time for
women. And Karola was a woman among women.
She laughed at him, and said something.
"We'd better take a look around," he said, carefully looking over her
golden head.
For many days the three wandered across the red grasslands of the
strange planet. Always they found an unbroken strata of rock crust
interlayered with lush lawnland. Occasionally a herd of tiny deer
swept by, and from these they made their meals.
Thor grew hard and tanned with the wild life. The muscles that had
seen him through lumber camp and football field waxed even
stronger. His clothes wore to thinness, and shredded in places.
Slowly he learned the jewel-language, and in turn Karola grew
familiar with his tongue.
He taught Slag to hurl his club, and wrestled with him when he felt
the need of violent exercise. The dwarf-man worshipped him, but he
entered into their games with feigned rage.
Karola told him something of her past. She was priestess of Klogor
on a small planet that swung around a sun invisible from Earth. Her
temple had been raided by the dwarf-men, and as she and Slag
struggled before an altar, something had come and snatched them
up, and whirled them around and around.
"Klogor is our god," said the girl. "I called on him, but he did not
hear. I was bred into his service, but he failed me in my need."
Slag rumbled, "This is my god," and shook his big club.
"You may need it," said Thor dryly. "Look!"
They were sitting on the edge of a rock, baking in the hot sun.
Below them spread the red meadows, rolling in even swells across a
valley toward jagged rocks that rose high into the pale sky. In the
middle of the meadow, ankle-high in the grass, three men were
standing.
Karola gasped, "They were not there a moment ago."
"The invisible men," commented Thor dryly, getting to his feet.
"They come and they go, and you can't see them do either."
Slag lifted his club, rumbling in his throat.
The men walked toward them slowly. They called out words. Fanning
into an arc, they came on. Now their hands fell to their sides and
they lifted long swords that dangled from the leather harness around
their middles.
Karola pulled her long legs up under the remnants of the gauze
trousers. Thor lifted her beside him with a hand. Side by side they
stood, awaiting the men.
"They have swords and we only have your club, Slag," said Thor.
"We want to work this together. Take the man at the left. I'll tackle
him, going for his sword, while you clout him. In that way, we'll each
have a weapon."
"And me?" asked Karola. "I can handle a blade. Priestesses of Klogor
are taught to defend themselves."
"We'll see. They're coming head-on for us. Careful, Slag. Go for your
man when I say the word."
His muscles tightened in his legs. This was like a football game, in a
way. The man with the sword was a ball carrier. Thor wanted that
sword more than he had ever wanted a football. He shifted his feet,
balancing himself.
"Now!"
They went off the rock together, dwarf and man.
Slag brought his club around in a vicious arc. Thor slid under it,
going for the arm. His fingers tightened on a wrist even as the club
crunched home. The sword came free. He grabbed at it. With his hip
he hit the man and drove him sideways into his companions.
Thor landed on his knees, the hilt of the blade in his right fist. He
looked around him, hearing Slag yell with superstitious fright.
Karola screamed from the rock, "They've disappeared!"
The meadows held only Slag and himself. Thor shook his head, and
looked at the grasses. Even against the red, there should be
bloodstains visible. But the blood had gone where the men had
gone.
"They don't even bleed," he said. "You sure you hit that guy, Slag?"
"Slag hit him!"
"I don't understand it. They come and go unseen. They must come
from somewhere. They must have dwelling places."
He lifted a long brown arm, thickly muscled. With it, he swept the
red grasslands, the grey rocks, the sky with its gigantic orb of sun.
For many days they had trod this world, and always found it as they
saw it now. Empty and barren, like a newborn planet.
Karola ran to catch them, and then the three walked on and on, into
the sunset.
Eight days later, they found the Discoverer. At first Thor thought him
another rock, so almost perfectly did his queer markings and
sprawling, bloblike form match the stone. And then when he moved,
in a peculiar, pouring sort of slide, and the electric tingles marched
up and down his spine, Thor knew he was alive.
"Hallo," called Thor.
The blotched thing swung about. There were no eyes to be seen in
its immense shape, but Thor knew he was being surveyed, and
closely.
"You are an Earthman," ran a thought in his mind. "The woman and
the man are Klogorons."
Thor said eagerly, "You know that? Then you must also know where
we are—how we came here?"
"I know, yes."
"And those men that come and go? And why we see no cities, no
habitations where they live? Do you know that too?"
"The Discoverer knows everything. I am the Discoverer. I live
everywhere and nowhere. Or at least I did until the madness that is
this queer space lapped out at me and brought me here, just as it
did you.
"To understand, you must think of the universe that you know as a
big, big bubble. It is stable and steady. It has its star clusters with
their space velocities and planetal orbits. Inside the big bubble
everything is orderly—except one thing.
"That one thing is a very tiny bubble. A sort of cancer, you might
say. It obeys no laws. Its very space coordinates and vectors are
different than ours. It is fluid—always in motion. Its space segments
are so alien that they can reach right through ordinary space,
annihilating distance, and seize upon objects."
"But that's nonsensical," protested Thor.
The Discoverer thought-beamed, "I said it is not space as we know
space. Let me put it this way: the magnet can draw metal to it
without touching the metal. So this space-cancer can attract objects
by reaching out for them, drawing them toward it—through a sort of
purplish mist—by some power of magnetic attraction."
Thor made a sound as if he understood, and the Discoverer went on,
"The segment of the rebel-universe came through the true universe,
and touched you—"
"Touched my house on the Midwestern campus."
"Yes. It drew you within itself—"
"But Karola and Slag! They came out of the air right in the middle of
my living room."
"They were in the magnetic pull, too. And where their space and this
space met, was the middle of your living room."
Thor looked at Karola, whose forehead was wrinkled in tiny furrows
as she followed the thoughts of the Discoverer. Slag was off to the
right, chasing a fat rabbit bounding ahead of him in terror.
The Discoverer went on, "I sought entrance to this world many eons
ago. It was one of the few spots in space I had never visited. Again
and again I sought to enter, but its strangely twisted space-time
continuum proved too much. Always I failed.
"And then, when I was visiting—I am almost all brain and it is a
habit of mine to roam a bit—I was visiting a planet of what you call
the Magellanic Cluster when everything went blank and I found
myself tugged through the purple space and landed here, stretched
across a rock."
Thor said, "You claim you can roam, mentally. Away from your body,
that is."
"Your world would call it astral projection, in which the spirit levitates
from the body and crosses distance. The high-energy potential of
the mind is used to dissociate the ethereal self, with which I include
the mental self, from the matter of the body."
Thor grunted dubiously, but the Discoverer went on, "I was engaged
in astral projection to the Magellanic Cluster when this space lapped
at my body that rested in the ruins of ancient Flormaseron. It is a
form of magnetic current that did the trick. Not ordinary magnetism,
but a current of it."
Thor thought of the Ehrenhaft experiments and nodded. He said,
"And what of this world where we are? We saw some men—"
"Not men. Androids. They are semi-human, invested by Aava with a
synthetic life-force."
"Aava?"
"Aava is the Green Flame. He rules this land. He is like nothing I
have ever seen. He can create, to an extent. He can destroy. He has
made androids to serve him, but he is limited in materials on this
planet. It is mostly rock and sand. If he had enough material, he
could make millions of the androids. As it is, he can, and has made
only thousands."
Thor said abruptly, "Can we get back to Earth and to Klogor?"
"Defeat Aava, learn the secret of this universe and destroy it, and
you may return."
"Aava. You called him the Green Flame. Where can I find him?"
Thor caught a flicker of humor in the thoughts that flooded his brain.
"Would you see Aava? I will show him to you. Lie down, on your
back. So. I warn you, control your thoughts. If Aava suspects he is
watched, you are doomed."
Karola pressed his arm against her warm side. Her violet eyes glared
in fear out of the white, lovely face. Her scarlet mouth begged, "Do
not do it, Thor. I beg you. I am afraid."
"There is nothing to fear. The Discoverer sounds as if he knows what
he's doing. And you do want to go back to Klogor, don't you?"
The girl flushed so that a delicate pale rose flooded her neck and
cheeks. Her violet eyes were brilliant as her torrent of gold hair
seemed to gather new brightness from the sun.
"I am not sure. It is a nice life, this roaming in open air, across great
prairies."
Thor held her hand. "You wait. I'll be back."
He lay down. His last recollection was the feel of Karola's long nails
pressing the flesh of his hand....
Thor hung bodiless in blackness. He was aware with all the five
senses of him, that life teemed about and all around the blackness,
that something walked and spoke and moved. Thor struggled until a
dull pain pounded and throbbed all through his being.
"Patient. Be patient," counseled a gentle voice.
"Are you the Discoverer?"
"I am he. It would be too dangerous to let you take your first
mentastral flight alone. Besides, your brain has not the electrical
potential sufficient to let you make progress. Hush, now. Listen!"
There were voices, deep and thunderous in a rolling wave of sound.
Dim and faint at first, the paean swelled and pulsed. And as the
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookball.com