简体   繁体   中英

Data from database is not showing

How can I get data from my database to show. I am not very experienced with PHP or MySQL.

I do not get an error message but no data shows so what am I doing wrong?

PHP

<?php
if(strlen(trim($_POST['search'])) > 0) {

$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";

mysql_connect ("cust-mysql-123-03", "", "");
mysql_select_db ("weezycouk_641290_db1");
if (!empty($_POST["search_string"])) 
{ 

}  

$query = "SELECT name,lastname,email FROM contact WHERE name LIKE '%$search%' AND 
lastname      LIKE '%$searchterm%'";

$result = mysql_query ($query);
echo mysql_error();
if ($result) {
while ($row = mysql_fetch_assoc($result)) {

echo $row["name"];
echo $row["lastname"];
echo $row["email"];
} ?>


<?php echo $row["name"]; ?>
<br>
<?php echo $row["lastname"]; ?>
<br>
<?php echo $row["email"]; ?>


<?php
}
}
?>

It should be like this:

<?php
if(strlen(trim($_POST['search'])) > 0) {

mysql_connect ("cust-mysql-123-03", "", "");
mysql_select_db ("weezycouk_641290_db1");

$query = "SELECT name,lastname,email FROM contact WHERE name LIKE '%" . mysql_real_escape_string($_POST['search']) . "%' AND lastname LIKE '%" . mysql_real_escape_string($_POST['searchstring']) . "%'";

$result = mysql_query ($query);
echo mysql_error();
if ($result) {
while ($row = mysql_fetch_assoc($result)) {

echo $row["name"];
echo $row["lastname"];
echo $row["email"];
} ?>


<?php echo $row["name"]; ?>
<br>
<?php echo $row["lastname"]; ?>
<br>
<?php echo $row["email"]; ?>


<?php
}
}
?>

The mysql_real_escape_string is to prevent mysql injection which is a serious risk.

Make sure the query you are executing returns record(s). You can check this by adding an echo statement which will print the query in your screen. Copy that and run it againist the database.You can use any mysql front end tools(php myadmin,mysqlyog to run the query. If there is any error in the query, you can see that then.

$query = "SELECT name,lastname,email FROM contact WHERE name LIKE '%$search%' AND 
lastname      LIKE '%$searchterm%'";
//the below line will print the query on the screen
echo $query;

$result = mysql_query ($query);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM