I've the following script (taken from a large script) saved as example3.php:
<script type="text/javascript">
var layer;
//where layer is a table like
------------------------------------
BUSNAME + Category +
------------------------------------
200 Bay + Restaurant +
201 Bay + Bank +
202 Bay + School +
203 Bay + Restaurant +
204 Bay + School +
205 Bay + Restaurant +
206 Bay + Restaurant +
207 Bay + School +
208 开发者_如何转开发Bay + Restaurant +
209 Bay + Restaurant +
------------------------------------
window.location.href = "example3.php?layer="+ layer;
<?php
//Make a MySQL Connection
$query = "SELECT Category, COUNT(BUSNAME)
FROM ".$_GET['layer']." GROUP BY Category";
$result = mysql_query($query) or die(mysql_error());
//Print out result
while($row = mysql_fetch_array($result)){
echo "There are ".$row['COUNT(BUSNAME)']. " " .$row['Category']. "items.";
echo "<br/>";
}
?>
</script>
Don't no why it is not working. Any suggestion must be appreciated.
if you have dynamical table name, your database design is wrong
as for your script, it just makes no sense.
make in in 2 parts: JS page and PHP page. and call this PHP page with window.location.href
I suggest JSON-encoding the table on the client side (in JS). Use POST to send it, then decode it on the server side (in PHP).
Most popular JS libraries do have JSON-encoding functions, the PHP function is called json_decode.
As Balus pointed out, watch out for SQL Injection. When you reach the php page, does the $_GET['layer']
equals something?
Does your javascript variable equals something?
var layer = "layer
"layer" being the actual name for the table inside of your database.
EDIT
In this context mysql_real_escape_string()
does not work.
$layer = mysql_real_escape_string($_GET['layer']);
$query = "SELECT Category, COUNT(BUSNAME)
FROM `".$layer."` GROUP BY Category"; <<-- this doesn't work.
Because mysql_real_escape_string does not escape backticks `
With values it does work
You need to run each and every value you get with $_GET
though mysql_real_escape_string(). (or use PDO's)
On top of that every value that you put into a query you need to enclose with single quotes '
.
$value = mysql_real_escape_string($_GET['fieldname']);
$query = "SELECT * FROM test WHERE f1 = '".$value."'"; <<-- this works
^ ^
Links:
SQL-injection attack: How does the SQL injection from the "Bobby Tables" XKCD comic work?
PDO's: mysqli or PDO - what are the pros and cons?
Will update as soon as I find a fix your your particular SQL-injection problem.
精彩评论