简体   繁体   中英

Connecting to MySQL DB and retrieving information

This is the first time I am using MySQL in a website and I need some help getting all setup. I have all my tables created and primary keys set, however I am a little lost on how to connect to the database and retrieve information. I added 1 sample album with albumdID 1 and 3 sample photos. Right now though I am not even sure if I am connecting to the database. I setup my config.php file also. I will post my code below, all this code is from my Index.php file. Thank you

       <?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);
?>

Do not mix mysql_* and mysqli_* functions. My advice: stick to mysqli_*

This example should get you going:

<?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);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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