Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

php - mysqli connection and query

I am new to mysqli and was going through a tutorial from: http://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17#comment1

I was able to connect to my database using this:

$config = parse_ini_file('../config.ini'); 
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if($connection === false) {
die('Connection failed [' . $db->connect_error . ']');
}
echo("hello"); //this worked!

But then I tried wrapping it in a function (as discussed in the tutorial)... I saw that you call the connection function from another function... in the tutorial each function keeps getting called from another and another... and I never quite found where the initial call started from to get the domino effect of functions calling eachother.. so anyway, I tried to stop it at two just to test and teach myself.. but it's not working and I don't know why:

function db_connect() {
static $connection;

if(!isset($connection)) {
$config = parse_ini_file('../config.ini'); 
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
    }
if($connection === false) {
return mysqli_connect_error(); 
}
return $connection;
echo("hello2");
}

function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
echo("hello1");

}

db_query("SELECT `Q1_Q`,`Q1_AnsA` FROM `Game1_RollarCoaster`"); //this didn't work :(
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well I ended up taking it out of the functions and made the code super simple (sticking with procedural instead of OOP even though a lot of tutorials use OOP - thought it was better to start this way):

<?php 
$config = parse_ini_file('../config.ini'); 
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);

if(mysqli_connect_errno()){  
echo mysqli_connect_error();  
}  


$query = "SELECT * FROM Game1_RollarCoaster";

$result = mysqli_query($link, $query);

while ($row = mysqli_fetch_array($result)) {

echo $row[Q1_Q] . '<-- Here is your question! ' . $row[Q1_AnsA] . '<-- Here is your answer! ';

echo '<br />';

}

mysqli_free_result($result);
mysqli_close($link);


?> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...