Erwin007 Posted July 21, 2023 Share Posted July 21, 2023 I have this code and it always gives me "ticket exists" even when it doesn't, where I go wrong? Thanks. $query = "SELECT * FROM sales WHERE sales_ticketnr = '$ticket' "; $result = mysqli_query($con,$query); if(!empty($result)) { echo '<script>alert("ticket exists")</script>'; } else { echo '<script>alert("ticket does NOT exist")</script>'; } Quote Link to comment Share on other sites More sharing options...
mac_gyver Posted July 21, 2023 Share Posted July 21, 2023 (edited) $result is a mysqli_result object. it will only be an empty() (false) value when the query fails due to an error. a query that matches zero rows is a successful query, not an error. if all you are doing is testing if a value exists in the database table, without wanting to fetch and use the matching data, use a SELECT COUNT(*) ... query, then fetch and test the count value. if you are going to use the fetched data, just fetch and test the value returned by the fetch statement. if this is for deciding if you are going to insert new data or update existing data, the column in question in the database table should be defined as a unique index, then you would just attempt to insert/update the row of data and test if a duplicate index error (number) occurred. next, don't put external, unknown, dynamic values directly into an sql query statement, where any sql special character in a value can break the sql query syntax, which is how sql injection is accomplished. use a prepared query instead. Edited July 21, 2023 by mac_gyver Quote Link to comment Share on other sites More sharing options...
Erwin007 Posted July 21, 2023 Author Share Posted July 21, 2023 I just want to know if there are zero rows or not. Quote Link to comment Share on other sites More sharing options...
Solution Barand Posted July 21, 2023 Solution Share Posted July 21, 2023 The first fetch() will return false if no records were found. if ($result->fetch_assoc()) { // ticket found } else { // ticket not found } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.