The challenge with using prepared statements in PHP/MySQL for inserting data into a form

Recently, I encountered an issue with the code below that takes information from a form and sends it to MySQL. Previously, everything was working fine for category, contents, date, and user ID fields. However, after adding a new column called 'seclevel' in the database, the code seems to have stopped functioning correctly. Despite not receiving any errors in the log, the addition of seclevel has somehow caused a disruption. It's worth noting that seclevel is just a user-selected integer ranging from 1 to 9. If anyone has insights into why this change might be causing issues, I'd greatly appreciate it.

send_post.php

<?php
include 'db_connect.php';
include 'functions.php';
sec_session_start();

$userId = $_SESSION['user_id'];
if(login_check($mysqli) == true) {

//Connecting to SQL db.
$connect=mysqli_connect("localhost","mylogin","mypass","mydb");

header("Location: http://somekindasite.com/index_3.php");

if (mysqli_connect_errno()) { echo "Fail"; } else { echo "Success"; }

//Sending form data to SQL db.
$stmt = $mysqli -> prepare('INSERT INTO opwire (category, contents, date, userid, seclevel) 
                            VALUES (?,?,NOW(),?,?)');
$stmt -> bind_param('ssi', $_POST['category'], $_POST['contents'], $userId, $_POST['seclevel']);
$stmt -> execute();
$stmt -> close();

} else {
   echo 'Access denied. <br/>';
}

?>

Here is the relevant form that submits to send_post.php

<html>
<div style="width:  330px;  height:  130px;  overflow:  auto;">
<form STYLE="color: #f4d468;" action="send_post.php" method="post">

    Category: <select STYLE="color: #919191; font-family: Veranda; font-weight: bold; font-size: 10px; background-color: #000000;" name="category">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option STYLE="color: #c31717;" value="8">8</option>
<option value="Other">Other</option>
</select>

    Seclevel: <select STYLE="color: #919191; font-family: Veranda; font-weight: bold; font-size: 10px; background-color: #000000;" name="seclevel">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select> <br>

    <textarea overflow: scroll; rows="4" cols="60" STYLE="color: #919191; font-family: Veranda; font-weight: bold; font-size: 10px; background-color: #000000; width:300px; height:80px; margin:0; padding:0;" name="contents"></textarea><br>
    <input type="submit" STYLE="color: #919191; font-family: Veranda; font-weight: bold; font-size: 10px; background-color: #000000;" value="Create Log">
</form>
</div>
</html>

Answer №1

The parameter binding in MySQLi involves two key components, and you seem to have overlooked one. Make sure to include the appropriate type indicator like s for string or i for integer (or d for double, b for blob) in the first argument of the bind_param() function.

// It appears you are trying to add another integer...
$stmt -> bind_param('ssii', $_POST['category'], $_POST['contents'], $userId, $_POST['seclevel']);
//---------------------^^^

It's crucial to implement error handling sincemysqli_stmt::bind_param() will return FALSE upon failure.

if ($stmt->bind_param('ssii', $_POST['category'], $_POST['contents'], $userId, $_POST['seclevel'])) {
  $stmt->execute();
}
else {
  echo $stmt->error;
}

I'd like to emphasize that I would have expected a fatal error from bind_param(). When writing code, it is always recommended to enable comprehensive error reporting and display errors on screen.

error_reporting(E_ALL);
ini_set('display_errors', 1);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify the input in text fields and checkboxes using JavaScript

I'm in the process of creating a complete "validate-form" function, but there are still a couple of things missing: Ensuring that the Name field only allows alphabetical characters and white spaces Validating that at least one checkbox is selected, ...

What is the best method to transfer and incorporate essays and information onto my HTML page?

Here are some unique events and observances for the month of December: DECEMBER 1 World AIDS Day National Pie Day National Eat a Red Apple Day Bifocals at the Monitor Liberation Day Day With(out) Art Day Rosa Parks Day DECEMBER 2 International Day for th ...

Curious about how to swap the positions of these two divs?

After wrapping them in divs and adding inline-block to both elements to display them side by side, I'm now exploring options to switch their positions. Specifically, I'd like the right element to be on the left. Any ideas on how to achieve this? ...

Generate a table using a text document

In an attempt to utilize a large data set from IMDB, I am working on transferring the data from a text file to a SQL database. Currently, my goal is to display the output in rows and columns format for easier insertion into a database. f = open("movies.l ...

Determine the position of each letter in the alphabet within a given string and calculate

Trying to find the position of an alphabet in a given string, calculating the length of the string, and obtaining the numeric position of the alphabet. For example, "Talha" has a length of 5, and finding "T" should return 1. <?php if(isset($_POST ...

What is the best way to successfully POST an array of dictionaries within another dictionary in Objective-C?

I have the knowledge and skills to tackle this task, it should be relatively straightforward. Unfortunately, despite my efforts, it's just not functioning properly. Below is the function I am utilizing to POST the data: - (void)updateWebsitesUsingP ...

How can I configure my React Project to direct users to example.com/login.html when they land on the root URL?

My goal is to verify a user's identity through a third-party authentication server. The redirect_uri indicates that after the user logs in, they will be redirected to example.com/login.html. Inside the login.html file, there will be specific html/scr ...

Is there a way to show a message when I hover over a different text?

I've been attempting to show a text when hovering over another text, but for some reason it's not working. I've followed all the steps from similar questions, but unfortunately, it still doesn't seem to be functioning correctly. Here i ...

Discrepancy in performance of jQuery.load function between local machine and remote server

When utilizing the jQuery.load function to create dynamic pages and sending data using the POST method, I encountered an issue. On my local PC (Windows with Apache/PHP server), everything worked perfectly. However, upon uploading it to my hosting server on ...

Laravel Eloquent model, text being cut off at maximum length

While working with Laravel, I encountered an issue when loading a database row into an Eloquent object. The problem arose from one of the columns being a longtext type containing a JSON encoded array with over 2 million characters. The original error I fac ...

Avoiding URL Error by Leveraging API for Cover Retrieval

I am facing an issue with my PHP website where I am unable to retrieve album covers. Previously, I used a JSON to obtain the Album ID and then used that ID to fetch the corresponding album cover. The problem now is that when I try to decode the JSON from ...

XSLT selecting the remaining elements in a tokenized array

In my XSL document, I have a requirement to generate a hyperlink with text that includes a line break, resulting in two separate sentences. To achieve this, I am utilizing the tokenize function to split words based on whitespace character. <xsl:variab ...

struggling to develop a sophisticated 'shopping cart organization' program

I am in the process of creating a database for video spots, where users can view and modify a list of spots. I am currently working on implementing a cart system that automatically stores checked spot IDs as cookies, allowing users to browse multiple pages ...

Dealing with unescaped double quotes in values while using JSON_VALUE()

I'm currently facing an issue with a table in my database where the field JSONDetail stores JSON data. The problem arose when we encountered unescaped double quotes within one of the values in this field, likely due to migrating from a system that all ...

Cursor vanishes until mouse movement detected (Chrome browser)

In the HTML page I created, the mouse cursor is initially set to none. However, there are certain circumstances where I need it to switch to crosshair. The issue I am facing is that the cursor does not appear unless the user moves the mouse. If the mouse r ...

Encountering a faulty handshake or ECONNRESET error connection in Azure Mysql while using

Issues with connecting to a mysql database hosted in Azure using an express.js app and KNEX have been troublesome. While I can successfully connect to the database from the console command or mysql workbench, my node app fails to do so. The connection ob ...

How to create list item bullets with a star icon using reactstrap/react?

As a machine learning professional looking to enhance my frontend skills, I am curious about how to create list item bullets using a custom star bullet image. Could anyone please share a complete HTML/CSS example with me? Thank you in advance! ...

What are the consequences of submitting a form to a different website through POST method?

Dealing with a CMS that does not offer an easy way to add a NodeJS route for handling form data can be quite challenging. I'm considering the following setup - would this be considered bad practice or unsafe? Server 1 (Ghost CMS) : www.domain.com &l ...

Encountering difficulties with the mobile display of a Wordpress theme

I am currently working with the megashop theme on WordPress and I have a few queries that need addressing: Is there a way to modify a specific setting exclusively for views smaller than desktop size, without impacting the desktop view? For example, the m ...

Deactivate user input depending on a certain requirement

Greetings everyone, I am currently working with the following code snippet: <table class="details-table" *ngIf="peop && peopMetadata"> <tr *ngFor="let attribute of peopMetadata.Attributes"> <td class="details-property"&g ...