在此代码中,我成功地从mySQL数据库中获取了五个随机文本字符串,并可以通过PHP回显它们。
与其通过 PHP 回显它们,我宁愿将它们显示为附加代码的画布中的文本(代替"Hello World"文本)。
关于我必须如何做到这一点的任何想法?
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
</script>
<?PHP
//CREATE CONNECTION
$con=mysqli_connect('localhost','','');
//select database
if(!mysqli_select_db($con,'test')) {
echo "database not selected";
}
//select query
//select random question
$sql=
"select * from `general knowledge`
order by rand()
limit 5";
//execute sql query
$records= (mysqli_query($con,$sql));
while ($row=mysqli_fetch_array($records)) {
echo "<P>";
echo "".$row['Question Text']."";
}
?>
把你的PHP代码块放在HTML块之前,然后通过这个来改变你的循环:
while ($row=mysqli_fetch_array($records)) {
$questions[] = $row['Question Text'];
}
这只是将 5 个问题放在一个名为 $questions 的数组中。
然后,当您生成 HTML 时,您可以执行以下操作:
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("<?= $questions[4]?>",10,50);
</script>
请注意注入带有 <?= ?>
标记的 PHP 值。然后,您可以注入五个问题中的任何一个。例如像这样:
ctx.fillText("<?= $questions[0]?>",10,50);
ctx.fillText("<?= $questions[1]?>",20,50);
ctx.fillText("<?= $questions[2]?>",30,50);
ctx.fillText("<?= $questions[3]?>",40,50);
ctx.fillText("<?= $questions[4]?>",50,50);
如果你真的想有一个循环(它真的那么有用吗?),你可以用PHP写一个:
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
<?php
foreach ($questions as $index => $question) {
echo " ctx.fillText('$question', 10+$index*10, 50);'n";
}
?>
</script>
您需要调整系数(现在是 10),您将乘以$index以获得文本之间的正确垂直距离。