Jump to content

Help needed with database search and update


andyroe208

Recommended Posts

Hi Guys,

I'm looking for a little help if possible please. I am new to php and programming in general. That being said I have took it upon myself to learn and taken on a project for work. I am creating a very simple inventory management system. The user will firstly search for a stockcode for it to be displayed in a table. So far so good. The table that  shows has 2 buttons with no current actions attached but upon pressing either an action is completed, the page is refreshed with an error. if an action is used on the button the response is the same error. I must be doing something wrong but for the life of me I can not see what. Any help would be appreciated. Please see below for my code.

search.php

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <title>Bootstrap 4 Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="apple-touch-icon" href="">
    <link rel="shortcut icon" href="" type="image/x-icon">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

    <!-- Link to your CSS file -->
    <link rel="stylesheet" href="/work/css/CD.css">
</head>

<body>
    <form class="form-signin" action="search_page.php" method="post">
      <div class="text-center mb-4">
        <img class="mb-4" src="/work/img/LogoCD18-300x190.jpg" alt="">
      </div>

      <div class="form-label-group">
        <input type="text" name="search" id="search" class="form-control text-center" placeholder="Stock Code">
        <label for="search" class="text-center">Stock Code</label>
      </div>

      <button class="btn btn-lg btn-primary btn-block" name="searchbutton" type="submit"><p>PRESS ME TO SEARCH</p></button>
      <p class="text-center bottom-align-text">Created using <a href="https://getbootstrap.com/">Bootstrap</a>, by <a href="">Andy Roe</a>.</p>

    </form>

    <!-- Coding End -->

    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
   <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
</body>
</html>

serach_page.php

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <title>Bootstrap 4 Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="apple-touch-icon" href="">
    <link rel="shortcut icon" href="" type="image/x-icon">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

    <!-- Link to your CSS file -->
    <link rel="stylesheet" href="/work/css/CD.css">
</head>

<body>
      <form class="form-signin">
   <div class="text-center mb-4">
    <table class="table table-striped table-dark">
   <tr>
       <th>Stock Code</th>
       <th>Boxes</th>
       <th>Location</th>
       <th>Actions</th>
   </tr>

    <!-- Coding End -->

    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
   <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>





<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "continental");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$get=$_POST['search'];
if ($get) {
    $show="SELECT * FROM stock where stockcode='$get'";
    $result=mysqli_query ($link,$show);
    while ($rows=mysqli_fetch_array ($result)) {
        echo "<tr>";
        echo "<td>";
        echo $rows['stockcode'];
        echo "</td>";
        echo "<td>";
        echo $rows['boxes'];
        echo "</td>";
        echo "<td>";
        echo $rows['location'];
        echo "</td>";
        echo '<td>';
        echo '<input type="number" name="stockadjust" id="stockadjust" class="form-control text-center mb-4" placeholder="Quantity">';
        echo '<button class="btn btn-lg btn-primary btn-block mb-4" name="addstockbutton"><p>ADD STOCK</p></button>';
        echo '<button class="btn btn-lg btn-primary btn-block mb-4" name="takestockbutton" type="submit" ><p>TAKE STOCK</p></button>';
        echo "</td>";
        echo "</tr>";
    }
}
else {
    echo "nothing found";
}

// close connection
mysqli_close($link);
?>


</table>
</div>
</body>
</html>

addtostock.php

<?php

// Escape user inputs for security
$stockcode = mysqli_real_escape_string($link, $_REQUEST['stockcode']);
$boxes = mysqli_real_escape_string($link, $_REQUEST['boxes']);
$location = mysqli_real_escape_string($link, $_REQUEST['location']);

// attempt insert query execution
$sql = "INSERT INTO stock (stockcode, boxes, location) VALUES ('$stockcode', '$boxes', '$location')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// close connection
mysqli_close($link);
?>

 

Link to comment
Share on other sites

There are many many problems with the Code posted.  Directly related to what you're asking is you are using one form with no Method type for multiple rows. Calling a POST  get is going to be confusing to people who know how to code. Short on time so I will have to answer more in detail later if someone else has not already provided more info on the code.

Link to comment
Share on other sites

When you see that you are duplicating code, in this case, the header and database connection code, you want to separate it to it's own file and include it in the files that need it. Next thing, you are dumping a bunch of JS files right smack in the middle of a table. You need to learn about "Separation of Concerns". You are also dumping the DB connection code the same way. Separate it to its on file and include it in the files that need it and not in the middle of a table.

Do not output internal system errors to the user. That info is only good to hackers. You need to check the server request method, not the name of a field or button. You don't need sixteen echo's to do the job of one. Even better, you should use the Php output tag and not have your HTML mixed in with Php.

There is no need to manually close the connection. Php will do it automatically. 

Clean up the code and you will be much less likely to have simple problems. I would also recommend you use PDO. Here is a tutorial to get you going. https://phpdelusions.net/pdo

Link to comment
Share on other sites

a bunch of recommendations, most of which will reduce and simplify the code, making it possible to spend more time on what the code is trying to accomplish, rather on spend time on the tedious implementation details -

1) put all the code on one page. the resulting code should be laid out as follows -

  1. initialization - code that defines, creates, or requires things the php code on the rest of the page needs to do its job.
  2. post method form processing - code to process $_POST data. note: your search form should use method='get'. post method forms are used when affecting data on the server or performing an action, such as sending email. get method forms/links are used when you are controlling what will be gotten and displayed on a page. the code to INSERT/UPDATE data in the database would be placed in this section of the code. it would first detect that a post method form was submitted, validate the input data, then if there are no validation errors, use the submitted data when the query is executed.
  3. get method 'business' logic - this is the code that knows how to retrieve or produce data that's needed to display the page.
  4. html document - the result from items 1-3 should be stored in php variables. these variables are the input data to html document. you can either use a 3rd party template engine or use simple php statements in the html document to take the input data and produce the dynamic sections of the html document.

2) validate all input data before using it. for your search form, what should happen if the page gets requested with no $_GET parameter? should you set up a default value or output an error message for the user (you probably don't want to generate php errors, which is what will happen now)? what should happen if the search string is empty? should the code match all rows or output an error message to the user telling them that the search term cannot be empty? if you store validation errors in an array, you can test at any point if there are or are not any errors by testing if the array is not empty or is empty. to display the errors at the appropriate point in the html document, either loop over the array or just implode it.

3) use exceptions to handle database statement (connection, query, prepare, execute) errors and in most cases let php catch the exception, where it will use its error_reporting, display_errors, and log_errors settings to control what happens with the actual error information. when learning, developing code/queries, and debugging problems, you should display all php errors. when code is running on a live/public server, you should log all php errors.

4) use prepared queries when supplying data to an sql query, with place-holders in the sql statement for each value, then supply the data when the query gets executed. you also need to switch to use the php PDO extension, it is much simpler and more consistent than the mysqli extension.

5) don't use SELECT * in sql query statements. list out the columns you want to select. this helps avoid mistakes and makes your code/query self-documenting.

6) only use php code for things that are 'dynamic'. if you are outputting mostly static html, don't waste your time typing a bunch of php echo statements around each line of it.

7) you need to validate the complete page at validator.w3.org

8 ) don't use $_REQUEST variables. if you expect post data, use $_POST variables. if you expect get data, use $_GET variables. if you expect cookie data, use $_COOKIE variables.

9) php automatically closes database connections when the script ends, so, you don't have to have code to do this.

10) you need to decide if and how you are going to update multiple rows of data. you currently have a single form (it's missing the closing </form> tag) with multiple submit buttons in it, which will cause all the form data to be submitted when any button is pressed. for this case, you should instead have one or two submit buttons before/after the program loop and only repeat the form data fields inside the program loop. also, in order to update multiple rows of data at once, the form field name(s) must be arrays with the array index being the id of the row of data that corresponds to each form field. when the array(s) of form data get submitted, you can use a foreach(){} loop to get the id and the value to use in a database query. an alternate method is to produce a separate form for each row of data, which will update just that row of data when the form is submitted.

11) your posted addtostock.php code doesn't have a database connection, so, if you manage to get your form to submit data to it, there will be a bunch of php errors associated with the connection. this problem will go-a-way when you put all the code on one page.

Link to comment
Share on other sites

Thank you benanamen and mac_gyver I appreciate your input,. As stated I am new to this and knew I would need to research some things, I didn't however realise the code was that bad ?. I will take on board all comments and research a lot more, all being well I will be able to achieve this simple project some time this year ?

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.