我无法弄清楚如何在PHP / MySql中显示此查询的结果。如果可能,我想使用准备好的声明。
SELECT count( DISTINCT(video_view_ip) ) FROM video_views
答案 0 :(得分:0)
从sql获取数据并使用php打印它请使用这种方式
首先连接到数据库
$con = mysqli_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysqli_select_db($con,"db_name");
并在连接后,从表中检索数据
$sql_fetch_vide_count = "SELECT count( DISTINCT(video_view_ip) ) as video_count FROM video_views ";
$video_result = $con->query($sql_fetch_vide_count);
if (!$video_result) {
die('Could not enter data: ' . mysql_error());
}
//getting the date to array
$row_video = $video_result->fetch_assoc();
//Fetch the count result
$video_count = isset($row_video ['video_count ']) ? $row_video ['video_count '] : 0;
如果从数据库中提取所有数据,请使用
$array_videos = array();
while ($row_video = $video_result->fetch_assoc()) {
$array_videos [] = $row_video ;
}
您可以将所有数据作为数组存入$ array_videos
答案 1 :(得分:0)
首先,我们需要获取与数据库的连接。为此,我们将使用PDO:
<?php
$config = [
'driver' => 'mysql',
'host' => 'localhost', // replace this with the actual mysql host if needed
'port' => 3306, // default mysql port is 3306
'database' => 'my_database', // replace this with the database you are using
'username' => 'admin', // replace this with your username
'password' => 'password', // replace this with your password
];
$connection = new PDO(
vsprintf('%s:Server=%s,%s;Database=%s', [
$config['driver'],
$config['host'],
$config['port'],
$config['database'],
]),
$config['username'],
$config['password']
);
要将配置保密,您可以将其存储在一个单独的只读文件中。然后,您可以使用parse_ini_file
阅读此配置。
要运行查询并存储结果,我们必须执行以下操作:
// in this case, we can use fetchColumn to retrieve the count, since it is a single value. However, we will usually want to use fetch() for most cases.
$count = $connection
->query('SELECT count( DISTINCT(video_view_ip) ) FROM video_views')
->fetchColumn();
要显示结果,我们只需echo
将其显示出来:
echo $count;
答案 2 :(得分:0)
检查这个例子,了解如何在php页面上生成输出 已编辑:在OP请求之前添加准备好的声明
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>