连接MySQL DB并检索信息

时间:2014-03-09 18:10:45

标签: php mysql

这是我第一次在网站上使用MySQL,我需要一些帮助才能完成所有设置。我创建了所有表并设置了主键,但是我对如何连接数据库和检索信息感到有点迷失。我添加了1张带有albumdID 1和3张样本照片的样本专辑。现在虽然我甚至不确定我是否连接到数据库。我也设置了我的config.php文件。我将在下面发布我的代码,所有这些代码都来自我的Index.php文件。谢谢

       <?php
// create the connection  (host, username, pw, dbname)
// and give feedback if that fails
$con = mysqli_connect('localhost', 'tmh233sp14', 'ECHOB8Se', 'info230_SP14_tmh233sp14');

// check connection
if (mysqli_connect_errno()) {
   printf('Connect failed: %s\n', mysqli_connect_error());
   exit();
}


// construct the query 
$albumID =1;
$sql = "SELECT Photos.photoID FROM Photos";
var_dump($sql);

// execute the query 
$query = mysqli_query($con, $sql);

// get the result set
$result = mysqli_fetch_array($query);

// iterate over result array to display stuff
var_dump($result); // for debugging use var_dump, to see whats inside

// close the connection
mysqli_close($con);
?>

1 个答案:

答案 0 :(得分:0)

不要混用mysql_ *和mysqli_ *函数。我的建议:坚持使用mysqli _ *

这个例子可以帮到你:

<?php
// create the connection  (host, username, pw, dbname)
// and give feedback if that fails
$con = mysqli_connect('localhost', 'tmh233sp14', 'password', 'info230_SP14_sjs334sp14');

// check connection
if (mysqli_connect_errno()) {
   printf("Connect failed: %s\n", mysqli_connect_error());
   exit();
}

// construct the query 
$albumId =1
$sql = "SELECT Photos.photoID, Photos.name FROM photos 
        LEFT JOIN photoInAlbum ON (photoInAlbum.photoID = Photos.photoID) 
        WHERE albumID = $albumID";

// execute the query     
$query = mysqli_query($con, $sql);

// get the result set
$result = mysqli_fetch_array($query);

// iterate over result array to display stuff
var_dump($result); // for debugging use var_dump, to see whats inside

// close the connection
mysqli_close($con);
?>