Monday 3 September 2018

MYSQL query does not work in php?

My mysql table has 6 fields bkid bkname bkauth bkpub bkedn bkstock. This program is just for testing you may see some extra lines which I have commented out because I am not using the commented lines for now. Just for now I am trying to get bkid from the html form and then use it in a query to find out the last column of the retrieved result in $row as $row[5] which is books in stock bkstock. So,I need to find out the no of books in stock from the bkid provided by the user in the form and clicking the button to submit the form.

The query given below does not work. Notice: Undefined offset: 5 in C:\xampp\htdocs\projects\library\incstockbook.php on line 41
<HTML>
<HEAD>
    <h1 align="center">THIS PAGE ADDS STOCK OF BOOKS TO THE LIBRARY</h1>
</HEAD>
TO INCREASE THE STOCK OF BOOKS TO INCLUDE TO THE LIBRARY
<FORM action="incstockbook.php" method="POST">
<table>
    <tr>
         <td>ENTER THE BOOK ID :</td>
         <td><input type=text name="bkid">
    </TR>
    <TR>
       <td>ENTER THE NO. OF BOOKS TO INCLUDE TO THE LIBRARY:</td>
       <td><input type=text   name="bkstock">
    </tr>
 </table>
 <BR>
 CLICK HERE STOCK MORE BOOK :<input type="submit"  value="ADD STOCK" name="submit"></br></br>
</FORM>
<?php
    $server="localhost";
    $username="root";
    $password="pramit";
    $db="test";
    $mysqli = new mysqli($server,$username,$password);
    if ($mysqli->errno)
    {
        printf("Unable to connect to the database:<br /> %s",
        $mysqli->error);
         exit();
    }
    $mysqli->select_db($db);
    $query1 = "select bkstock from books where bkid=";
    if(isset($_POST['submit']))
    {
        $bkid=$_POST['bkid'];
       // $bkstock=$_POST['bkstock'];
        $query1.="'$bkid'";
        $result=$mysqli->query($query1,MYSQLI_STORE_RESULT);
        $row = $result->fetch_array(MYSQLI_NUM);
        echo "$row[5]";
    }
    $mysqli_close;
?>


First thing to do in such cases is to use var_dump(). It'll tell you what is in $rowvariable and allow you to fix that problem. And problem is the fact that you're trying to get sixth item from row when there is only one, so it should be $row[0].
But there are some more to fix here. Check $mysqli_close; statement, maybe you wanted to use $mysqli->close()? Because like that it doesn't make any sense.
Next, never use raw user input data in queries. It's dangerous! You have to filter it, or better use prepared statements.

0 comments:

Post a Comment