change from mysql to mysqli - php

I wrote code that allow me to get information from mysql using mysql which is old code, and i tried to change to mysqli from mysql but some how is not working right, I believe that i'm still new to learn about mysqli, can any one help me to to write into mysqli from mysql so i can learn myself from there please... here is code...
thanks...
<?php
include('db.php');
?>
<?php
if(isset($_POST['kw']) && $_POST['kw'] != '')
{
$kws = $_POST['kw'];
$kws = mysql_real_escape_string($kws);
$query = "select * from product where product_name like '%".$kws."%' limit 10" ;
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
echo "<ul>";
while($row = mysql_fetch_array($res))
{
echo "<a href='$row[product_name]'><li>";
echo "<div id='rest'>";
echo $row['product_name'];
echo "<br />";
echo "<td>";?><img src="<?php echo $row["screenshot"];?>" height="100" width="100" <?php echo "</td>" ;
echo "</div>";
echo "<div style='clear:both;'></div></li></a>";
$i++;
if($i == 5) break;
}
echo "</ul>";
if($count > 5)
{
echo "<div id='view_more'><a href='#'>View more results</a></div>";
}
}
else
{
echo "<div id='no_result'>No result found !</div>";
}
}
?>

The general rule of thumb is:
Do not change.
But write mysqli version from scratch.
As your approach with old mysql ext were all wrong, do not translate it to new mysqli. Just learn mysqli and then write the whole thing from scratch.
Otherwise you'd better leave your old code as is, just because such a mechanical rewriting will do not a slightest good.

Related

ELSE condition is not working in the while loop in PHP

<?php
$conn=mysqli_connect("localhost","id6755695_artemi8","sharanod"
,"id6755695_user_info");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$department = $_POST["department"];
$year = $_POST["year"];
$sem = $_POST["semester"];
$reg = $_POST["regulation"];
$sql = "SELECT book_name, author, edition, image FROM dept_search WHERE
department='$department' AND year='$year' AND semester='$sem' AND
regulations='$reg' ";
$result=mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result))
{
if($row)
{
echo "<br>";
?>
<img src=" <?php echo $row['image']; ?> " height="300" width="300">
<?php
echo "<br>";
echo "<b>",$row['book_name'],"</b>";
echo "<br>";
echo $row['author'];
echo "<br>";
echo $row['edition'];
}
else
{
echo "sorry book not found";
}
}
mysqli_close($conn);
?>
please help me with this code,i am building a library management system.. The thing is I should be able to display the books if the given values are present i have in the database if not book not found must be displayed but in while loop after if, else does not runs.....
As others have pointed out, your else statement will never run. If you are already inside the while loop, you will certainly have $row defined and for that reason, else will never run.
What you can do is, check beforehand if the query returned actual results, like so:
$result=mysqli_query($conn,$sql);
if($result->num_rows > 0){
while($row = mysqli_fetch_assoc($result)){
echo "<br>";
?>
<img src=" <?php echo $row['image']; ?> " height="300" width="300">
<?php
echo "<br>";
echo "<b>",$row['book_name'],"</b>";
echo "<br>";
echo $row['author'];
echo "<br>";
echo $row['edition'];
}
}else{
echo "Sorry book not found";
}
You can try with mysqli_num_rows .. sample code as follows :
$rowcount=mysqli_num_rows($conn,$sql);
if($rowcount!=0){
$result=mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result))
{
echo "<br>";
?>
You are looping through all the rows returned from the "mysqli_fetch..." command. Your "if" and "else" is useless -- you will always have rows. If you get no rows, you do not even enter the body of the while loop.
You need to COUNT the rows returned (count($row)) and display a message that nothing was found if the count is less than one.
All you need to do is that you have to change if the condition from if($row) to if($other_condition)
Currently, you are just checking either there is something inside $row, and this condition will never be wrong unless you will assign it null. Because where $row will have something then while loop will be executed, and when while loop will be executed then if condition will be executed.
you have to simply one thing, that is to change if condition like given below...
if($row['value'] == 'something')

php echo if query is empty

I'm querying a database but when the result is empty i want to output a table row displaying "nothing to display" but the if seems to always return true.
Here's my code...
$priorityincidentsQ = mysql_query("SELECT * FROM applications WHERE pi >= ('2') ");
while($priorityincidentsR = mysql_fetch_object($priorityincidentsQ))
{
if (empty($priorityincidentsR)) {
echo "<tr><td class=\"closedcallscell centered\"><b>Nothing to display</b></td></tr>";
} else {
echo "<tr><td class=\"closedcallscell\"><b>$priorityincidentsR->application_friendly_name</b></td>";
echo "<td class=\"closedcallscell table_row_small\"><center>$priorityincidentsR->pi</center></td></tr>";
}
}
Use mysqli_num_rows() to check is there any result:
$conn = mysqli_connect($host, $user, $password, $database);
$priorityincidentsQ = mysqli_query($conn, "SELECT * FROM applications WHERE pi >= ('2') ");
if (mysqli_num_rows($priorityincidentsQ) > 0){
while ($priorityincidentsR = mysqli_fetch_object($priorityincidentsQ)) {
echo "<tr><td class=\"closedcallscell\"><b>$priorityincidentsR->application_friendly_name</b></td>";
echo "<td class=\"closedcallscell table_row_small\"><center>$priorityincidentsR->pi</center></td></tr>";
}
}else{
echo "<tr><td class=\"closedcallscell centered\"><b>Nothing to display</b></td></tr>";
}
And yes, better use mysqli_* functions instead of mysql_*.
Still never figured out why this wouldn't work out for me this way, I tried the query directly in SQL workbench and everything looks how it should, I ended up solving the problem like this.
<!-- priority incidents-->
<?php
$priorityincidentsQ = mysql_query("SELECT * FROM applications WHERE pi >= ('1') ");
while($priorityincidentsR = mysql_fetch_object($priorityincidentsQ))
{
echo "<tr><td class=\"closedcallscell\"><b>$priorityincidentsR->application_friendly_name</b></td>";
echo "<td class=\"closedcallscell table_row_small\"><center>$priorityincidentsR->pi</center></td></tr>";
}
?>
<!-- if no incidents-->
<?php
$incidentNumberofRowsQ = mysql_query("SELECT COUNT(*)numberofrows FROM applications WHERE pi >= ('1') ");
while($incidentNumberofRowsR = mysql_fetch_object($incidentNumberofRowsQ))
{
if ($incidentNumberofRowsR->numberofrows == '0')
{
echo "<tr><td class=\"closedcallscell centered\"><b>Currently no priority incidents</b></td>";
}
}
?>
may seem a rather silly way of going about it but atleast it works. Thanks all for the help. :)

Produce dynamic link from array

I have a searchpage, which works fine. Search results are displayed in a table with tr hover and a window.location to take the user to a different page.
What I am trying to achieve is a dynamic link for the window.location based on data from the array. All the data in the db belongs to 4 different categories, testkat, and I would like to direct the user to the right page depending on the value from testkat, and then using the 'testid' to fill in the data.
I have been trying numerous ways to achieve my goal, and searched both SE, Google etc, but no luck. I'm pretty new to PHP so using the right search term might have something to do with it.
From my point of view I'm thinking that I have to store the value from testkat in a variable, lets say $link. And from there make an IF statement, something like:
if ($results('testkat') == 'something') {
$link = "something.php?id='$testid'";
}
if ($results('testkat') == 'something_else') {
$link = "something_else.php?id='$testid'";
}
And from there put $link in the window.location
Here's my code:
<?php
$conn = mysql_connect("localhost", "root", "") or die("Couldn't do it: ".mysql_error());
mysql_select_db("db") or die(mysql_error());
mysql_set_charset('utf8',$conn);
$query = $_POST['query'];
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
$raw_results = mysql_query("SELECT * FROM db WHERE (`id` LIKE '%".$query."%') OR (`name` LIKE '%".$query."%') OR (`age` LIKE '%".$query."%')") or die(mysql_error());
$count = mysql_num_rows($raw_results);
if(isset($_POST['query'])) {
echo "<br>";
echo "Your search for <span class=\"bold\">" .$query. "</span> returned " . $count . " hits";
echo "<br>";
if(mysql_num_rows($raw_results) > 0){
echo "<br>";
echo "<table class=\"tbl-text\">";
echo "<tr class=\"tablelist\"><th>Heading 1</th><th>Heading 2</th><th>#</th><th>Heading 3</th><th>Heading 4</th><th>Heading 5</th>";
while($results = mysql_fetch_array($raw_results)){
echo "<tr onclick=\"window.location='#'\" style=\"cursor:pointer\" class=\"tr-hover\">";
echo "<td class=\"bordered\">" .$results['testid'] . "</td>";
echo "<td class=\"bordered\">" .$results['testkat'] . "</td>";
echo "<td class=\"bordered\">" .$results['intnr'] . "</td>";
echo "<td class=\"bordered\">" .$results['pro'] . "</td>";
}
echo "</table>";
}
else{
}
}
?>
Update:
Forgot to tell about the error. When doing it the way I think it should be done, I get an error message in the IF statement saying: Fatal error: Function name must be a string.
Referring to this one:
if ($results('testkat') == 'something') {
$link = "something.php?id='$testid'";
}
I know about MySQLi and PDO, working on it.
Eager to learn, so any hints and tricks are greatly appreciated :)
Chris
That method looks fine. You don't need the single quotations around $testid though
$link = "something_else.php?id=$testid";
As you've mentioned you should stop using mysql, get learning :)
Managed to fix it, and posting if someone else are having the same problem.
First, rewrote the whole thing to MySQLi.
Then I put an IF statement after the WHILE LOOP like this:
Connecting to db ->
if(isset($_POST['query'])) {
$query = $_POST['query'];
$query = htmlspecialchars($query);
$sql = $db->query("SELECT * FROM db WHERE (`?` LIKE '%".$query."%') OR (`?` LIKE '%".$query."%') OR (`?` LIKE '%".$query."%')");
$result = mysqli_query($db, sql);
$hits = $sql->num_rows;
echo "<br>";
echo "Your search for <span class=\"bold\">" .$query. "</span> returned " . $hits . " results";
echo "<br>";
if($sql->num_rows > 0){
echo "<br>";
echo "<table class=\"tbl-text\">";
while ($row = mysqli_fetch_array($sql)) {
if ($row['category'] == 'cat01'){
$link = 'cat01.php?id=' . $row['testid'] . '';
}
if ($row['category'] == 'cat02'){
$link = 'cat02.php?id=' . $row['testid'] . '';
}
if ($row['category'] == 'cat03'){
$link = 'cat03.php?id=' . $row['testid'] . '';
}
if ($row['category'] == 'cat04'){
$link = 'cat04.php?id=' . $row['testid'] . '';
}
echo "<tr onclick=\"window.location='$link'\" style=\"cursor:pointer\" class=\"tr-hover\">";
echo "<td class=\"bordered\">" .$row['testid'] . "</td>";
>>> more echo
}
There are probably more efficient ways to do this, but at least I got the results I was after, and the script is also more secure now using MySQLi

Added if else argument and lost variable from database

<?php
$con=mysqli_connect("localhost","root","","clarks");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$place = $_GET['place'];
$place2 = $_GET['place2'];
$return = $_GET['return'];
$people = $_GET['people'];
$pickup = $_GET['pickup'];
$dropoff = $_GET['dropoff'];
$result = mysqli_query($con,"SELECT * FROM pricelist WHERE place1='$place' AND place2='$place2' AND people='$people'");
while($row = mysqli_fetch_array($result))
{
if (!empty($row['Price']))
{
echo "Not Applicable";
}
else
{
echo "<html><body style='background-color: #31ff01;'><link rel='stylesheet' href='css/bootstrap.min.css'>";
echo "<div id='prices'>£";
echo $row['Price'] * $return + $pickup + $dropoff;
echo "</div>";
echo "<div id='back'>";
echo "<a href='index.html'>Go Back</a>";
echo "</div>";
echo "<br>";
}
}
mysqli_close($con);
?>
This is returning the "Not Applicable" from the if argument every time.
I've tried placing the lines in different order and using both the price and result variable, it still only returns not applicable but without the if else argument, the rest of it works as intended and brings up a price so I know the price variable shouldn't be empty and neither should the result variable.
With it returning not applicable all the time, I assume it's not retrieving the information from the database properly any more but I can't figure out why when it works perfectly fine without the if else.
Any help would be great, Thanks.
Your logic is wrong:
if (!empty($row['Price']))
^ here
{
echo "Not Applicable";
}
should be:
if (empty($row['Price']))
{
echo "Not Applicable";
}
You also have a serious sql injection problem, you should use prepared statements or at the very least use mysqli's escaping function.
if (empty($row['Price']))
{
echo "Not Applicable";
}
else
{
echo "<html><body style='background-color: #31ff01;'><link rel='stylesheet'
.....
}
}
I think the in the if condition the negation causes the problem
Remove the exclamation mark!
It might be because you are using mysqli_fetch_array instead of mysqli_fetch_assoc. http://www.php.net/manual/en/mysqli-result.fetch-assoc.php
You should also start using real_ escape_ string on your parameters, or do it in the right way with parameterized prepared statement. http://www.php.net/manual/en/mysqli.prepare.php
<?php
$con=mysqli_connect("localhost","root","","clarks");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$place = $_GET['place'];
$place2 = $_GET['place2'];
$return = $_GET['return'];
$people = $_GET['people'];
$pickup = $_GET['pickup'];
$dropoff = $_GET['dropoff'];
$result = mysqli_query($con,"SELECT * FROM pricelist WHERE place1='$place' AND place2='$place2' AND people='$people'");
$row = (mysqli_fetch_array($result));
$a = $row[3];
if (empty($a))
{
echo "<html><body style='background-color: #31ff01;'><link rel='stylesheet' href='css/bootstrap.min.css'>";
echo "<div id='prices'>";
echo "N/A";
echo "</div>";
echo "<div id='back'>";
echo "<a href='index.html'>Go Back</a>";
echo "</div>";
echo "<br>";
}
else
{
echo "<html><body style='background-color: #31ff01;'><link rel='stylesheet' href='css/bootstrap.min.css'>";
echo "<div id='prices'>£";
echo $a * $return + $pickup + $dropoff;
echo "</div>";
echo "<div id='back'>";
echo "<a href='index.html'>Go Back</a>";
echo "</div>";
echo "<br>";
}
mysqli_close($con);
?>
Well I found this workaround, instead of using while I just got rid of it and assigned the price from the database into its own variable meaning there's no conflict with the if else statement. Works like a charm... now to look at prepared statements :S

SQL Not Found Condition

I have a php script that tries to find a particular name in a database where the specified program is $q, a variable passed from an html page. I'm very new to this so I'm having trouble figuring out how to code an if not found, then display type of message. Below is what I currently have:
$sql="SELECT * FROM names WHERE program='".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<div class='header'>Program Name:</div>";
echo "<div class='data'>";
echo $row['program'];
echo "</div>";
}
And I need it to echo a message saying if nothing was found. I tried looking at NOT IN condition in SQL and http://www.techonthenet.com/sql/exists.php along with other things on the internet but I'm not sure if this is the right thing to use. Any help would be appreciated.
use th php function
mysql_num_rows($result);
to check results found
So your code should be like:
$sql="SELECT * FROM names WHERE program='".addslashes($q)."'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
while($row = mysql_fetch_array($result))
{
echo "<div class='header'>Program Name:</div>";
echo "<div class='data'>";
echo $row['program'];
echo "</div>";
}
else
echo "No data found";
please note i added
addslashes($q)
in query, in order to avoid SQL injection problems.
$sql="SELECT * FROM names WHERE program='".$q."'";
$result = mysql_query($sql);
$found = false;
while($row = mysql_fetch_array($result))
{
$found = true;
echo "<div class='header'>Program Name:</div>";
echo "<div class='data'>";
echo $row['program'];
echo "</div>";
}
if ($found == false)
echo "I found nothing";

Categories