简体   繁体   中英

Problems with displaying mysql results

<?php  

include('../Adress/includes/mysql_connection_recepti.php');

if (isset($_POST['username'])){

$conn = dbConnect($_POST['username']);


$city=$_POST['city'];

$sql= 'SELECT * FROM adress_table WHERE city="'.$city.'"';

$result=mysql_query($sql);

$numRows=mysql_num_rows($result);

?>

<p><?php echo $numRows; ?> records is found.</p>

<table>
<tr>
<th>Number</th>
<th>Name</th>
<th>Last Name</th>
<th>City</th>
<th>Country</th>
<th>Date</th>
</tr>

<?php 
$n=0;

while($row = mysql_fetch_assoc($result)){
//print_r($row);

$n++;

?>

<tr>
<td><?php echo $n . ".";?></td>
<td><?php echo $row['name'] ?></td>
<td><?php echo $row['last_name'] ?></td>
<td><?php echo $row['city'];?></td>
<td><?php echo $row['country'] ?></td>
<td><?php echo $row['date'] ?></td>
</tr>

<?php }?>

</table>

<?php }?>
</body>
<body>

<form action="" method="post">
<input type="text" id="username" name="username"/>


<select name="city">
<option value="new_york">New York</option>
<option value="london">London</option>
<option value="belgrade">Belgrade</option>
<option value="zagreb">Zagreb</option>
<option value="moscow">Moscow</option>

<input type="submit" value="Find">
</select>
</body>

As you can see, my sql statement tells that every column has to be displayed when city="'.$city.'", and that is completely ok. But when I try to display some particular column(s), not all (*), for example

$sql= 'SELECT name,last_name FROM adress_table WHERE city="'.$city.'"';

then error emerges, bacause

 <td><?php echo $row['city'];?></td>
 <td><?php echo $row['country'] ?></td>
 <td><?php echo $row['date'] ?></td>

are not defined. In order to fix this I put @ sign

 <td><?php @ echo $row['city'];?></td>
 <td><?php @ echo $row['country'] ?></td>
 <td><?php @ echo $row['date'] ?></td>

to cover up error messages and I cat tell you that everything looks perfectly all right, but I don't know is it good practice. What should I do? Thanks.

您可以使用if来检查其中是否有东西:

<?php echo isset($row["city"]) ? $row["city"] : "" ?>

You are trying to display a column that is not present in your SQL query. YOu can use something like -

<?php echo isset($row["city"]) ? $row["city"] : "" ?>

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