我最近用准备好的语句修复了我的旧的和难以置信的MySQL查询。但是,当我运行这个新查询时,除了使用print_r进行调试时,不会返回任何值。如果仅回显值(即echo $ eventid),则会收到无法将数组转换为字符串的错误。我是否需要向该查询添加某种foreach循环?非常感谢你们继续帮助我学习! :)
<?php
echo "<div class='container target'>
<div class='container'>
<div id='quick-access'>
<form class='form-inline quick-search-form' role='form'>
<div class='form-group'>
<input type='text' id='name' name='name' class='form-control' placeholder='Driver name'>
</div>
<button type='submit' id='quick-search' class='btn btn-custom'><span class='glyphicon glyphicon-search custom-glyph-color'></span></button>
</form>
</div>
</div>";
?>
<?php
$conn = new mysqli('localhost', 'Username', 'password', 'Database');
if($conn->connect_errno > 0)
{
die('Unable to connect to database [' . $conn->connect_error . ']');
}
# SQL WITH QMARK PLACEHOLDER (USING TABLE ALIASES)
$sql = "SELECT e.personaId, e.ID AS event_id, e.EVENTID, e.rank, e.carId,
e.alternateEventDurationInMilliseconds,
p.iconIndex, p.cash, p.level, p.created, p.score, p.motto,
p.repAtCurrentLevel, p.rep, p.name AS p_name
FROM EVENT_DATA e
INNER JOIN PERSONA p ON e.personaId = p.ID
WHERE (p.name = ? AND e.EVENTID = '43'
AND e.alternateEventDurationInMilliseconds > '0')";
# INITIALIZE ARRAYS - TWO METHODS: array() or []
$name = array(); $avatarimg = []; $cash = array(); $level = array(); $createddate = [];
$driverscore = array(); $motto = []; $repcurrent = array(); $reptotal = [];
$personaid = array(); $eventid = []; $milliseconds = array();
# PREPARED STATEMENT
$stmt = mysqli_prepare($conn, $sql) or die(mysqli_error($conn));
# BIND PARAM
$param=mysqli_real_escape_string($conn, $_GET['name']);
mysqli_stmt_bind_param($stmt, "s", $param);
# EXECUTE STATEMENT
if (mysqli_stmt_execute($stmt)){
$result = $stmt->get_result();
# CHECK ROWS
if(mysqli_num_rows($result) > 0) {
# ITERATE THROUGH ROWS
while ($row = mysqli_fetch_array($result)){
# APPEND TO ARRAYS
$name[] = mysqli_real_escape_string($conn, $row['p_name']);
$avatarimg[] = mysqli_real_escape_string($conn, $row['iconIndex']);
$cash[] = mysqli_real_escape_string($conn, $row['cash']);
$level[] = mysqli_real_escape_string($conn, $row['level']);
$createddate[] = mysqli_real_escape_string($conn, $row['created']);
$driverscore[] = mysqli_real_escape_string($conn, $row['score']);
$motto[] = mysqli_real_escape_string($conn, $row['motto']);
$repcurrent[] = mysqli_real_escape_string($conn, $row['repAtCurrentLevel']);
$reptotal[] = mysqli_real_escape_string($conn, $row['rep']);
$personaid[] = $row['personaId'];
$eventid[] = $row['EVENTID'];
$milliseconds[] = $row['alternateEventDurationInMilliseconds'];
}
}
}
print_r($name);
print_r($eventid);
?>
答案 0 :(得分:1)
使用$name[] = mysqli_real_escape_string($conn, $row['p_name']);
时,它将选择查询的每个单个结果添加到数组中。这就是为什么当您尝试回显时它不起作用的原因。
这是一种简单的查看方法。
foreach ($name as $n) {
echo $n . '<br />';
}