I need to show specific record, record exist in db but it showing nothing. Here my code is.
$con=mysqli_connect("localhost","root","","test") or die("Connecting to MySQL failed");
$name=$_POST['uname'];
$query = "SELECT * FROM officedb WHERE name='.$name.'";
$data=mysqli_query($con,$query);
while($row=mysqli_fetch_array($data)){
echo $row['name'];
echo $row['lname'];
echo $row['department'];
}
The .
is the concatenation operator. It is used to put multiple strings or variables together. Inside double quotes, PHP parses variables, so this is not necessary. Additionally, inside either single or double quotes, "." will be treated as a literal period, not the concatenation operator.
But that's not why I'm adding this answer... Putting a post straight into a query is asking for all sorts of bad behavior, which would crash your web application, cause you to lose data, have data compromised, or worse. Research SQL injection and Little Bobby Tables. You're already using MySQLi, which is good, but bring it home...
So, what should be done? Use prepared statements.
$name=$_POST['uname']; /* NEVER TRUST user input. This value
could be very dangerous!!! */
$con=mysqli_connect("localhost","root","","test") or die("Connecting to MySQL failed");
$stmt = $con->prepare("SELECT * FROM `officedb` WHERE name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$data = $stmt->get_result();
while($row=mysqli_fetch_array($data)){
// I assume these came from user input too. Do not trust when printing.
echo htmlspecialchars($row['name']);
echo htmlspecialchars($row['lname']);
echo htmlspecialchars($row['department']);
}
See the bind_param PHP Manual page for more information. Additionally, you should not trust user input when printing back to html. Use htmlspecialchars to help with that (when printing to html, not when adding to DB).
Please consider making this the accepted answer so newcomers do not stumble upon dangerous code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With