我开始为我的小型房地产业务创建一个网站。 我玩了一些函数http://www.php.net mysql,我设法通过AJAX访问页面并返回搜索引擎的html内容。
我有一个已经填充了公寓和房屋的数据库
问题是,如果公寓名称是“公寓”,我会返回html内容,如果“有3个房间的公寓”它不再写任何东西。
我不明白我错在哪里:
<?php
$search = $_GET['selected'];
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('houses', $link);
function searchHouse($search, $link){
$query = "select * from houses where name=$search limit 1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query2 = "select * from houses_info where house_id=$row[id]";
$result2 = mysql_query($query2);
$row = mysql_fetch_assoc($result2);
return $row;
}
$result = searchHouse($search, $link);
echo $result['house_sq'];
echo "<br>";
echo $result['house_rooms'];
echo "<br>";
echo $result['house_bathrooms'];
echo "<br>";
echo $result['house_address'];
?>
答案 0 :(得分:5)
mysql_*
函数已被弃用且不再维护。它是页面顶部的红色框,告知您。MySQL
注射孔,你根本没有逃脱$string
$string
添加引号,例如:'$string'
PDO
来删除错误的代码和SQL注入漏洞。您可以将这两个选项包装到一个选择中:
<?php
function searchHouse($search, $link){
$search = mysql_real_escape_string($search);
$query = "select * from houses_info where house_id IN (select * from houses where name='".$search."' limit 1)";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
return $row;
}
?>
由于您已构建该网站,因此可以开始转到PDO
,请阅读此tutorial,您的代码将更像是这样:
<?php
$db = new PDO('mysql:host=localhost;dbname=houses;charset=UTF-8', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$search = $_GET['selected'];
function searchHouse($search){
global $db;
$query = $db->prepare("select * from houses_info where house_id IN (select * from houses where name=:search limit 1)");
$query->execute(array(':search' => $search));
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row;
}
$result = searchHouse($search);
?>
答案 1 :(得分:0)
尝试:
$query = "select * from houses where name='".mysql_real_escape_string($search)."' limit 1";
并且记得在将用户输入传递给sql之前始终清理用户输入以避免sql注入。
答案 2 :(得分:-2)
需要在查询中引用字符串。此外,这很容易受到MySQL注入,请确保使用mysql_real_escape_string转义$ search。或者甚至更好地使用MySQLi或PDO而不是旧的mysql_函数。
$query = "select * from houses where name=$search limit 1";
应该是:
$query = "select * from houses where name='$search' limit 1";
虽然你真的需要逃避$ search,因为它来自用户,即使它们不是恶意的,任何带有单引号的搜索查询都会中断;
$search = $_GET['selected'];
应该是:
$search = mysql_real_escape_string($_GET['selected']);
(任何人都可以通过指向MySQLi / PDO教程的链接获得复制粘贴吗?)
答案 3 :(得分:-2)
您的第一个查询应该是:
$ query =“select * from houses where name of $ search%limit 1”;