简体   繁体   English

将mySQL数据库中的数值分配给PHP变量时,最佳方法是什么?

[英]What is the best method to use when assigning a numerical value from a mySQL database to a PHP variable?

I'm attempting to grab a number value from a mySQL database using PHP. 我正在尝试使用PHP从mySQL数据库中获取数字值。 I'd like to use that number value for some calculations after I've assigned it's value to a variable. 在将数值分配给变量后,我想将该数值用于某些计算。 The number value is stored as a float in my database. 数字值以浮点数形式存储在我的数据库中。 My code attempts to connect to my database (which it does successfully), then pull a number value based on parameters passed on by my query, then apply that number value to a variable that I can use in my code. 我的代码尝试连接到我的数据库(它成功完成),然后根据查询传递的参数提取一个数字值,然后将该数字值应用于可以在我的代码中使用的变量。 In my code below, I'm simply trying to print that value to make sure it's pulling properly. 在下面的代码中,我只是尝试打印该值以确保其正确拉出。 The result I get is this notice: Notice: Array to string conversion in /Users/max/Desktop/Sites/webprojects/prg/nba/percentchange.php on line 14 Array 我得到的结果是这样的通知:注意:第14行数组/Users/max/Desktop/Sites/webprojects/prg/nba/percentchange.php中的数组到字符串的转换

Here's my code: 这是我的代码:

$mysqli = new mysqli('localhost', 'root', 'root', 'NBA');

            if (mysqli_connect_errno()) {
                echo '<p>Error: could not connect to database.</p>';
                exit;
            }

            $rank = "SELECT average FROM nbaCompRankings WHERE team = 'Celtics'";
            $result = $mysqli->query($rank);
            $currentRank = $result->fetch_assoc();

echo $currentRank; echo $ currentRank;

The potential solutions I've found on this site use deprecated libraries, so I've been unsuccessful in a search for a solution. 我在该站点上找到的潜在解决方案使用了不推荐使用的库,因此在寻找解决方案方面我一直没有成功。 Thanks in advance for any help you can give! 在此先感谢您提供的任何帮助!

Try This: 尝试这个:

$result = $mysqli->query($rank);
while($row = $result->fetch_assoc()) {
    $currentRank = $row["average"];
}

You should really be preparing your statements though. 不过,您实际上应该在准备您的声明。

$team = 'Celtics';
$sql= "SELECT average FROM nbaCompRankings WHERE team = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $team);
$stmt->execute();
$stmt->bind_result($average);
while($stmt->fetch()) {
    $currentRank = $average;
}
$stmt->close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM