Loading JavaScript Arrays with MySQL Data 1st edition by Alex Ressi - Read the ebook online or download it as you prefer
Loading JavaScript Arrays with MySQL Data 1st edition by Alex Ressi - Read the ebook online or download it as you prefer
com
https://ebookball.com/product/loading-javascript-arrays-
with-mysql-data-1st-edition-by-alex-ressi-14054/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookball.com/product/learning-php-mysql-javascript-css-and-
html5-a-step-by-step-guide-to-creating-dynamic-websites-3rd-edition-
by-robin-nixon-isbn-1491906979-9781491906972-15996/
ebookball.com
https://ebookball.com/product/client-server-web-apps-with-javascript-
and-java-1st-edition-by-casimir-
saternos-1449369316-9781449369316-20258/
ebookball.com
https://ebookball.com/product/learning-mysql-get-a-handle-on-your-
data-1st-edition-by-saied-mm-tahaghoghi-hugh-e-williams-
isbn-0596529465-9780596529468-15988/
ebookball.com
https://ebookball.com/product/javascript-data-structures-and-
algorithms-an-introduction-to-understanding-and-implementing-core-
data-structure-and-algorithm-fundamentals-1st-editon-by-sammie-bae-
isbn-1484239873-9781484239872-15798/
ebookball.com
DNA Arrays Technologies and Experimental Strategies 1st
Edition by Elena Grigorenko ISBN 9781420038859 1420038850
https://ebookball.com/product/dna-arrays-technologies-and-
experimental-strategies-1st-edition-by-elena-grigorenko-
isbn-9781420038859-1420038850-9724/
ebookball.com
https://ebookball.com/product/lncs-2832-efficient-algorithms-for-the-
ring-loading-problem-with-demand-splitting-1st-edition-by-biing-feng-
wang-yong-hsian-hsieh-li-pu-yeh-isbn-3540200649-978-3540200642-13034/
ebookball.com
https://ebookball.com/product/immediate-loading-of-dental-implant-1st-
edition-by-mithridade-davarpanah-serge-
szmukler-9782912550507-2912550505-7570/
ebookball.com
https://ebookball.com/product/automating-the-design-of-data-mining-
algorithms-an-evolutionary-computation-approach-2010th-edition-by-
gisele-pappa-alex-freitas-isbn-3642025402-9783642025402-9878/
ebookball.com
https://ebookball.com/product/analyzing-business-data-with-excel-1st-
edition-by-gerald-knight-9780596553463-0596553463-12548/
ebookball.com
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
Another Random Document on
Scribd Without Any Related Topics
El acto está sujeto á ciertas reglas, que se observan como todas las
reglas humanas, hasta que se puede.
Se inicia con un yapaí, que es lo mismo que si dijéramos: the
pleasure of a glass of wine with you? para que vean los de la colonia
inglesa que en algo se parecen á los ranqueles.
Pero esta invitación se diferencia algo de la nuestra.
Nosotros empezamos por llenar la copa del invitado, luego la propia;
bebemos simultáneamente, haciéndonos un saludo más ó menos
risueño y cordial, espiándonos por sobre el borde de la copa, á ver
quién la apura más; y es de buena educación, de estilo clásico, no
beberla toda, ni tampoco que parezca se ha aceptado el brindis por
compromiso; como que él significa:—Á la salud de usted cuando no
se ha propuesto uno por la patria, por la libertad ó por el Presidente
de la República.
Los indios empiezan por decir yapaí, llenando bien el tiesto en que
beben, que generalmente es un cuernito.
La persona á quien se dirigen, contesta yapaí.
Bebe primero el que invitó, hasta poder hacer lo que los franceses
llaman goute en l'ongle, es decir, hasta que no queda una gota,
llenan después el vaso, copa, jarro ó cuernito exactamente, como él
lo bebiera, se lo pasa al contrario, y éste se lo echa al coleto
diciendo yapaí.
Si el yapaí ha sido de media cuarta, media cuarta hay que beber.
Por supuesto que no conozco nada peor visto que una persona que
se excusa de beber, diciendo:—No sé.
En un hombre tal, jamás tendrían confianza los indios.
Así como en toda comida bien dirigida, hay siempre un anfitrión que
la preside, que hace los honores, que la anima; así también en todo
beberaje de indios hay uno que lleva la palabra; es el que hace el
gasto, por lo común.
Esta vez, el que hacía el gasto ostensiblemente era Mariano Rosas,
en realidad el Estado, que le había dado sus dineros al Padre Burela
para rescatar cautivos.
Pero aunque Mariano Rosas hacía el gasto y era el dueño de la casa,
Epumer, su hermano, era el anfitrión.
Epumer es el indio más temido entre los ranqueles, por su valor, por
su audacia, por su demencia cuando está beodo.
Es un hombre como de cuarenta años, bajo, gordo, bastante blanco
y rosado, ñato, de labios gruesos y pómulos protuberantes, lujoso en
el vestir, que parece tener sangre cristiana en las venas, que ha
muerto á varios indios con sus propias manos, entre ellos á un
hermano por parte de madre, que es generoso y desprendido,
manso estando bueno de la cabeza, que no estándolo le pega una
puñalada al más pintado.
Con este nene tenía que habérmelas yo.
Llevaba un gran facón con vaina de plata cruzado por delante, y me
miraba por debajo del ala de un rico sombrero de paja de Guayaquil,
adornado con una ancha cinta encarnada, pintada de flores blancas.
Yo llevaba un puñal con vaina y cabo de oro y plata, sombrero gacho
de castor, y alta ala, no le quitaba los ojos al orgulloso indio,
mirándole fijamente cuando me dirigía á él.
Bebíamos todos.
No se oía otra cosa que ¡yapaí, hermano! ¡yapaí, hermano!
Mariano Rosas no aceptaba ninguna invitación, decía estar enfermo,
y parecía estarlo.
Atendía á todos, haciendo llenar las botellas cuando se agotaban;
amonestaba á unos, despedía á otros cuando me incomodaban
mucho con sus impertinencias; me pedía disculpas á cada paso; en
dos palabras, hacía, á su modo, y según lo usos de su tierra,
perfectamente bien los honores de su casa.
Epumer no había simpatizado conmigo, y á medida que se iba
caldeando, sus pullas iban siendo más directas y agudas.
Mariano Rosas lo había notado, y se interponía constantemente
entre su hermano y yo, terciando en la conversación.
Yo le buscaba la vuelta al indio y no podía encontrársela.
Á todo lo hallaba taimado y reacio.
Llegó á contestarme con tanta grosería que Mariano tuvo que
pedirme lo disculpara, haciéndome notar el estado de su cabeza.
Y sin embargo, á cada paso me decía:
—Coronel Mansilla, ¡yapaí!
—Epumer, ¡yapaí!—le contestaba yo.
Y llenábamos con vino de Mendoza los cuernos y los apurábamos.
Mis oficiales se habían visto obligados á abandonar la enramada, so
pena de quedar tendidos, tantos eran los yapaí.
Los indios, caldeados ya, apuraban las botellas, bebían sin método;
¡vino! ¡vino! pedían para rematarse, como ellos dicen, y Mariano
hacía traer más vino, y unos caían y otros se levantaban, y unos
gritaban y otros callaban, y unos reían y otros lloraban, y unos
venían y me abrazaban y me besaban, y otros me amenazaban en
su lengua, diciéndome winca engañando.
Yo me dejaba manosear y besar, acariciar en la forma que querían,
empujaba hasta darlo en tierra al que se sobrepasaba demasiado, y
como el vino iba haciendo su efecto, estaba dispuesto á todo. Pero
con bastante calma para decirme:
—Es menester aullar con los lobos para que no me coman.
Mis aires, mis modales, mi disposición franca, mi paciencia, mi
constante aceptar todo yapaí que se me hacía, comenzaron á
captarme simpatías.
Lo conocí y aproveché la coyuntura.
La ocasión la pintan calva.
Llevaba una capa colorada, una linda, aunque malhadada capa
colorada, que hice venir de Francia, igual á las que usan los oficiales
de caballería de los cuerpos argelinos indígenas.
Yo tengo cierta inclinación á lo pintoresco, y durante mucho tiempo,
no he podido substraerme á la tentación de satisfacerla.
Y tengo la pasión de las capas,—que me parece inocente, sea dicho
de paso.
En el Paraguay usaba capa blanca siempre.
Hasta dormía con ella.
Mi capa era mi mujer.
Pero qué caro cuestan á veces las pasiones inocentes.
Por usar capa colorada me han negado el voto de los comicios.
Por usar capa colorada me han creído colorado.
Por usar capa colorada me han creído caudillo de malas intenciones.
Pero entonces, ¿cómo dicen que el hábito no hace al monje?
Decididamente, Figueroa es quien tiene razón. «Pues el hábito hace
al monje, por más que digan que no».
Me quité la histórica capa, me puse de pie, me acerqué á Epumer, y
dirigiéndole palabras amistosas, le dije:
—Tome, hermano, esta prenda, que es una de las que más quiero.
Y diciendo y haciendo, se la coloqué sobre los hombros.
El indio quedó idéntico á mí, y en la cara le conocí que mi acción le
había gustado.
—Gracias, hermano—me contestó, dándome un abrazo que casi me
reventó.
Vi brillar los ojos de Mariano Rosas, como cuando el relámpago de la
envidia hiere el corazón.
Tomé mi lindo puñal, y dándoselo, le dije:
—Tome, hermano, usted úselo en mi nombre.
Lo recibió con agrado, me dió la mano y me lo agradeció.
Mandé traer mi lazo que era una obra maestra y se lo regalé á
Relmo.
Ya estaba en vena de dar hasta la camisa.
Mandé traer mis boleadoras, que eran de marfil con abrazaderas de
plata, y se las regalé á Melideo.
Mandé traer mis dos revólveres y se los regalé á los hijos de
Mariano.
Llevaba tres sombreros de los mejores, llevaba medias, pañuelos,
camisas, regalé cuanto tenía.
Y por último mandé traer un barril de aguardiente y se lo regalé á
Mariano.
Mariano me dijo:
—Para que vea, hermano, cómo soy yo con los indios, delante de
usted les voy á repartir á todos. Yo soy así, cuanto tengo es para mis
indios, ¡son tan pobres!
Vino el barril y comenzó el reparto por botellas, calderas, vasos,
copas y cuernos.
En tanto que Mariano hacía la patriarcal distribución, un hombre de
su confianza, un cristiano, se acercó á mí y á voz baja me dijo:
—Dice el general Mariano que si trae más aguardiente le guarde un
poquito para él, que esta noche cuando se quede solo piensa
divertirse solo; que ahora no es propio que él lo haga.
¿Qué te parece cómo se hila entre los indios?
Contesté que tenía otro barril, que repartiese todo el que acababa
de recibir.
La orgía siguió; era una bacanal en regla.
Epumer comenzó á ponerse como una ascua, terrible.
Mariano quiso sacarme de allí: me negué, su hermano quería beber
conmigo y yo no quería abandonar el campo, exponiéndome á las
sospechas de aquellos bárbaros.
Soy fuerte, contaba conmigo.
Si la fortuna no me ayudaba, alguna vez se acababa todo, algún día
termina esta batalla de la vida en que todo es orgullo y vanidad.
—Yapaí—me dijo Epumer, ofreciéndome un cuerno lleno de
aguardiente.
—Yapaí—contesté horripilado;—yo podía beber una botella de vino
en una sentada. Pero un cuerno, al mejor se la doy.
En ese instante y mientras Epumer apuraba el cuerno, una voz
suave me llamó al oído.
Di vuelta sorprendido, y me hallé con una fisonomía infantil, pero
enérgica.
—Y ¿quién eres tú?
—Un cristiano, Miguelito.
XXVII
Pasión de Miguelito.—Los hombres son iguales en todas
circunstancias de la vida.—Retrato de Miguelito.—Su
historia.
ebookball.com