mysqli连接和查询 [英] mysqli connection and query

查看:83
本文介绍了mysqli连接和查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是mysqli的新手,并且正在阅读以下教程:

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 :(

推荐答案

好吧,我最终将其从函数中删除,并使代码超级简单(即使很多教程使用OOP,也要坚持使用过程式而不是OOP-思想最好以这种方式开始):

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


?> 

这篇关于mysqli连接和查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆