douqian1296 2015-12-01 22:36
浏览 44
已采纳

使用sqli php动态生成html

I am trying to dynamically create html content based on the results of a mysql query on my personal web project. I had thought I had found the solution, but then realized I was mixing PHP apis and I shouldn't do that. For a few other pages, I learned about prepared statements and got through re-writting a lot of my php handlers. But I'm not sure how to replicate something like this...

<?php
$teacherid = 1;
$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
$dbname = "xxxx";

$conn = new mysqli($servername, $username, $password, $dbname);

if($conn->connection_error){
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT ClassID, className FROM Classes WHERE teacherID = '" . $teacherid . "' ;";
$result = $conn->query($sql);

while($row = $result->fetch_assoc()){
    echo ("<a class='button href=\"class.php?id=".$row["ClassID"]."\">".$row["className"."</a>");
}

Appache gives me the error result:

Object of class mysqli_result could not be converted to string in /var/../../page.php

on this line of code

$sql = "SELECT ClassID, className FROM Classes WHERE teacherID = '" . $teacherid . "' ;";

vardump($teacherid) produces the following:

object(mysqli_result)#1 (5){["current_field"]}=>NULL ["field_count"]=>NULL ["lengths"]=>NULL ["num_rows"]=>NULL ["type"]=>NULL}

It appears that my session variable was somehow dropped somewhere in my website... before tracking that down I wanted to see this method for creating content work. I changed $teacherid to this...

$teacherid = 1; 

I also changed $sql to

$sql = "SELECT ClassID, className FROM Classes WHERE teacherID = " . $teacherid . " ;";

Now, no buttons are being created, but I am also not receiving any error from Appache. The exact same query used directly on sql will return 1 valid result, however.

A solution to the session var was also found here: Notice: Unknown: Skipping numeric key 1 in Unknown on line 0

  • 写回答

1条回答 默认 最新

  • dongxi8297 2015-12-01 22:44
    关注

    You have some syntax mistakes so I need to write you before anything and maybe is this what you need

    while($row = $result->fetch_assoc()){
        echo "<a class=\"button\" href=\"class.php?id=".$row["ClassID"]."\">".$row["className"]."</a>";
    }
    

    Also $teacherid in your query is not defined anywhere

    Edit: Again you have syntax error in your echo

    echo ("<a class='button href=\"class.php?id=".$row["ClassID"]."\">".$row["className"."</a>");
    

    You missed to close brackets for row['ClassName'];

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 Ubuntu20.04无法连接GitHub
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥30 C++行情软件的tick数据如何高效的合成K线