php mysql, mysql_query() expects parameter 2 to be resource
/*这是可行的<html><head></head><body><?$conn=mysql_connect('localhost','root','f3r5tqfp')o...
/*这是可行的
<html>
<head>
</head>
<body>
<?
$conn = mysql_connect('localhost','root','f3r5tqfp')or die('Could not connect ' .mysql_error());
echo 'Connected successfully';
if (mysql_query("create database my_db",$conn))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
}
?>
</body>
</html>
*/
当我修改成这样,mysql_query怎麼我把原先my_db转为形参就发生问题
Warning: mysql_query() expects parameter 2 to be resource, null given in /Applications/XAMPP/xamppfiles/htdocs/dropDownMenu/css80.php on line 10
Error creating database:
<html>
<head>
</head>
<body>
<?
$conn = mysql_connect('localhost','root','f3r5tqfp')or die('Could not connect ' .mysql_error());
echo 'Connected successfully';
function createDB($db)
if (mysql_query("create database $db",$conn))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
}
createDB('my_db');
?>
</body>
</html> 展开
<html>
<head>
</head>
<body>
<?
$conn = mysql_connect('localhost','root','f3r5tqfp')or die('Could not connect ' .mysql_error());
echo 'Connected successfully';
if (mysql_query("create database my_db",$conn))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
}
?>
</body>
</html>
*/
当我修改成这样,mysql_query怎麼我把原先my_db转为形参就发生问题
Warning: mysql_query() expects parameter 2 to be resource, null given in /Applications/XAMPP/xamppfiles/htdocs/dropDownMenu/css80.php on line 10
Error creating database:
<html>
<head>
</head>
<body>
<?
$conn = mysql_connect('localhost','root','f3r5tqfp')or die('Could not connect ' .mysql_error());
echo 'Connected successfully';
function createDB($db)
if (mysql_query("create database $db",$conn))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
}
createDB('my_db');
?>
</body>
</html> 展开
2个回答
展开全部
变量作用域的问题。
$conn在function中的时候是局部变量,且未定义,所以会报那个错误。
可以这样写
<?
$conn = mysql_connect('localhost','root','f3r5tqfp')or die('Could not connect ' .mysql_error());
echo 'Connected successfully';
function createDB($db,$conn)
if (mysql_query("create database $db",$conn))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
}
createDB('my_db',$conn);
?>
Ps: 如果db是外界传递过来的名字,建议进入function后执行sql之前 对$db做下check,防止这里注入
$conn在function中的时候是局部变量,且未定义,所以会报那个错误。
可以这样写
<?
$conn = mysql_connect('localhost','root','f3r5tqfp')or die('Could not connect ' .mysql_error());
echo 'Connected successfully';
function createDB($db,$conn)
if (mysql_query("create database $db",$conn))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
}
createDB('my_db',$conn);
?>
Ps: 如果db是外界传递过来的名字,建议进入function后执行sql之前 对$db做下check,防止这里注入
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |