我更新了我的代碼。它有Javascript,PHP,JSON和JQuery。我正在閱讀來自 MySQL數據庫的X,Y座標。 我現在使用的3個文件:coordinate_array,db_conn和map.phpMySql和PHP循環用x,y座標繪製正方形
連接:
<?php
//declaring connection
$db_user = "u";
$db_pwd = "p";
$db_server = "v";
$db_name = "sandbox";
//1. connection to the database
$conn = mysqli_connect($db_server, $db_user, $db_pwd);
//check connection
if(!$conn){
die("Database connection failed: " . mysqli_error());
}else{
echo "connected to MySQL<br>";
}
// 2. Select a database to use
$db_select = mysqli_select_db($conn, $db_name);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
mysqli_close($conn);
?>
在coordinate_array:我想提出一個多維數組,所以我可以畫出所有的矩形被我的查詢獲取 ,然後使用json_encode($ desk)。我忽略表 中的coordinate_id,因爲我只需要Javascript部分的x,y值。
<?php
$select_coordinate_query = "SELECT * FROM coordinates";// WHERE coordinate_id ='1'
$result = mysqli_query($conn,$select_coordinate_query);
//see if query is good
if($result === false) {
die(mysqli_error());
}
//array that will have number of desks in map area
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk = array(array("x" => $row['x_coord']),
array("y" =>
$row['y_coord'])
);
// Frame JSON
// Return the x, y JSON here
echo json_encode($desk);
} //end while loop
?>
在map.php:我試圖獲得與使用jQuery的那些價值。我想獲取這些值並運行一個 循環,該循環將執行我的Paint函數,該函數將爲 表中的每一行保留繪製矩形。我對JSON和JQuery非常新,並開始使用它。
<div class="section_a" >
<p>Section A</p>
<canvas id="imageView" width="600"
height="500"></canvas>
<script type="text/javascript">
$(document).ready(function(){
/* call the php that has the php array which is json_encoded */
$.getJSON('coordinate_array.php', function(data) {
/* data will hold the php array as a javascript object */
if(data != null){
$.parseJSON(data);
$(data).each(Paint(x,y)){
//get values from json
//for every row run the functionpaint by passing X,Y coordinate
});//end getJson
}//end if
}); //end rdy func
});//end func
//function to paint rectangles
function Paint(x,y)
{
var ctx, cv;
cv = document.getElementById('imageView');
ctx = cv.getContext('2d');
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
//x-axis,y-axis,x-width,y-width
ctx.strokeRect(x, y, x+100 , y+100);
}
</script>
</div> <!-- end div section_a -->
而且,我做了正確的語法,包括我的jQuery的文件時,我..其在相同 ,我使用所有其他文件。
另一個問題我有是:這是很好的,包括在每一個文件的連接文件,並在年底 關閉或保持連接在我的文件打開,我havethe建立連接?
非常感謝!
不是一個答案,但你提出的代碼是不可維護的混亂。至少不要在一個文件中混合使用HTML,JS,PHP和SQL。 – Andrey 2014-09-29 18:11:18
您正在爲您從數據庫中提取的每組座標創建一個新畫布。我相信這不是你想要做的。另外,不要使用'mysql _ *()' - 它已被棄用。使用'mysqli _ *()'作爲新代碼。 – 2014-09-29 18:17:36
請注意,MySQL爲座標系統數據提供了[http://dev.mysql.com/doc/refman/5.5/en/spatial-datatypes.html](本地支持)。你不應該使用'mysql _ *()'或''mysqli _ *()';而是使用PDO或其他抽象層。 是的,如果你需要一些有用的建議來改善它,請分開你的代碼。 – miken32 2014-09-29 22:02:43