php - Adding text from mySQL query onto canvas -
in code, 5 random text strings mysql database, , can echo them via php.
instead of echoing them via php, rather display them text in canvas (in place of "hello world" text) of attached code.
any ideas of how have go doing this?
<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 * `general knowledge` order rand() limit 5"; //execute sql query $records= (mysqli_query($con,$sql)); while ($row=mysqli_fetch_array($records)) { echo "<p>"; echo "".$row['question text'].""; } ?>
put php code block before html block, , change loop have this:
while ($row=mysqli_fetch_array($records)) { $questions[] = $row['question text']; }
this puts 5 questions in array called $questions.
then when generate html, can things this:
<script> var c = document.getelementbyid("mycanvas"); var ctx = c.getcontext("2d"); ctx.font = "30px arial"; ctx.filltext("<?= $questions[4]?>",10,50); </script>
notice injection of php value <?= ?>
tag. can inject 1 of 5 questions. instance this:
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);
if want have loop (is useful?), write 1 in php:
<script> var c = document.getelementbyid("mycanvas"); var ctx = c.getcontext("2d"); ctx.font = "30px arial"; <?php foreach ($questions $index => $question) { echo " ctx.filltext('$question', 10+$index*10, 50);\n"; } ?> </script>
you'll need adapt factor (it 10) multiply $index right vertical distance between texts.
Comments
Post a Comment