The goal:
- Connect to database using php to extract results
- Loop through results
- Store results in a way such that the are accessible during run-time
How I tried to do this:
- SQL query to get data
- Create function with inputs of column data that outputs this data as a javascript object
- Store javascript object in javascript array (not yet done)
For some reason (which may or may not be obvious to a more trained eye) I am running into a bug.
Note: database connection works perfectly, and the proper results are fetched with no issues. The issue is 100% the way I am trying to execute my javascript via php. I am assuming the php is seeing the var etc and is compiling it.
Please advise on the code below and if more specifics are needed I will happily expand:
<?
if (!isset($_COOKIE['authPw'])){
echo '<script>window.location="http://www.google.com"</script>';
}
?>
<html>
<head>
</head>
<body>
<?
function jsEcho($i,$cN,$fN,$lN,$pN,$eM){
$jString="var appObj = new Object();";
$jString+="appObj.id=" + $i + ";";
$jString+="appObj.companyName=\'" + $cN + "\';";
$jString+="appObj.firstName=\'" + $fN + "\';";
$jString+="appObj.lastName=\'" + $lN + "\';";
$jString+="appObj.phoneNumber=\'" + $pN + "\';";
$jString+="appObj.eMail=\'" + $eM + "\';";
//echo "1ONE1".$jString."2TWO2";
return $jString;
}
$host="localhost"; // Host name
$username="abc"; // Mysql username
$password="def"; // Mysql password
$db_name="ghi"; // Database name
$tbl_name="jkl"; // Table name
$link=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$mySQL="select * from ".$tbl_name.";";
echo $mySQL;
$result=mysql_query($mySQL);
$jS="var aApps=new Array();";
while ($row = mysql_fetch_array($result))
{
$iD=$row["id"];
$companyName=$row["companyName"];
$firstName=$row["firstName"];
$lastName=$row["lastName"];
$phone=$row["phone"];
$email=$row["email"];
$jS+=jsEcho($iD,$companyName,$firstName,$lastName,$phone,$email);
}
?>
</body>
<?
echo '<script>';
echo $jS;
echo '</script>';
?>
</html>
Your script is after the body element closes. That’s not valid html. Possibly it is not being evaluated. I suspect the output is also not valid javascript either.
Also, your jsEcho method is verbose, unsafe, and unnecessary. Use this pattern: