从Mysql / PHP获取名称或UserID的用户信息
问题描述:
Can I know what's mistake in here? I have two tables in my database. it is this
I have written the code as search player thing. I'll put the name or userid in the form and it'll process the information of user.
Here is my code
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="term" />
<input type="submit" value="Submit" />
</form>
<?php
include('config.php');
if (!empty($_REQUEST['term']))
{
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = " select u.* from users u inner join ranks r ON (u.UserID = r.UserID) where u.UserID = '%" . $term . "%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query))
{
echo 'Name: ' . $row['Name'];
echo '<br /> Cash: ' . $row['Cash'];
echo '<br /> Score: ' . $row['Score'];
echo '<br /> Race: ' . $row['Race'];
echo '<br /> Horseshoe: ' . $row['Horseshoe'];
}
}
?>
</body>
</html>
</div>
答
First of all you should update your config.php
to mysqli_
functions.
and the mysqli_real_escape_string()
and mysqli_query()
functions need 2 Parameters.
First $conn
, second: the variable
finally your code should look like this:
<html lang="en">
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<form method="POST">
Search: <input title="searchfield" required type="text" name="term"/>
<input type="submit" name="submit" value="Submit"/>
</form>
<?php
include('config.php');
if (isset($_POST["submit"]) && !empty($_POST["submit"])) {
$term = mysqli_real_escape_string($conn, $_REQUEST["term"]); //make sure the $conn isset
$sql = "SELECT u.* FROM users u INNER JOIN ranks r ON (u.UserID = r.UserID) WHERE u.UserID LIKE '%" . $term . "%'"; // change = to LIKE
$r_query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($r_query)) {
echo 'Name: ' . $row['Name'];
echo '<br /> Cash: ' . $row['Cash'];
echo '<br /> Score: ' . $row['Score'];
echo '<br /> Race: ' . $row['Race'];
echo '<br /> Horseshoe: ' . $row['Horseshoe'];
}
}
?>
</body>
</html>
your config.php
should look like this:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "idkw0t";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
答
you should use like
in query as follows
$sql = " select u.* from users u inner join ranks r ON (u.UserID = r.UserID) where u.UserID like '%" . $term . "%'";