我正在从我的数据库中读取x和y坐标,计算有多少行与我在画布上绘制的点数重合:
<?php
$conn = mysqli_connect("localhost","root","","login");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT id FROM sample";
if ($result = mysqli_query($conn,$sql)){
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($conn);
?>
var val = '<?php echo $rowcount;
?>';
我想使用数据库中给定的x和y位置绘制点。 我正在尝试使用循环来使用多维数组从数据库中绘制所有点,这就是我的问题所在。我在如何解决它时遇到了困难
for(var i = 0; i < val; i++)
{
<?php
$conn = mysqli_connect("localhost","root","","login");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM sample";
if ($result = mysqli_query($conn,$query)){
$points= array( array("x" => $row['x']),
array("y" => $row['y']));
//x, y coordinates
$x_pos = $points['x'];
$y_pos = $points['y'];
mysqli_free_result($result);
}
mysqli_close($conn);
?>
var x = '<?php echo $x_pos; ?>';
var y = '<?php echo $y_pos; ?>';
ctx.beginPath();
ctx.arc(x , y, 2, 0, 2 * Math.PI, false);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
答案 0 :(得分:0)
正如我在评论中所指出的,您将PHP代码嵌入到javascript循环中,假设PHP代码将在循环的每次迭代中运行。然而,事实并非如此。 PHP代码在服务器上运行,并在循环内部呈现一次。然后循环在浏览器上运行迭代相同的值。
这是我想你想写的:
<?php
$conn = mysqli_connect("localhost","root","","login");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM sample";
echo 'var points=[';
if ($result = mysqli_query($conn,$query)) {
foreach( $result as $row ) {
echo "{x:${row['x']}, y:${row['y']}},";
}
mysqli_free_result($result);
}
echo "];\n";
mysqli_close($conn);
?>
for(var i = 0; i < points.length; i++) {
var p = points[i];
ctx.beginPath();
ctx.arc(p.x , p.y, 2, 0, 2 * Math.PI, false);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
以下是对上述代码的解释:
PHP代码在服务器上运行,查询数据库并将数据点作为javascript变量声明/初始化回显。回显的变量声明以及以下javascript代码将发送到浏览器并在那里运行。 javascript代码遍历数组变量并创建路径。