Jump to content

someone show me why this code doesn't submit data into my db table


simbae
 Share

Recommended Posts

error_reporting(E_ALL);

        ini_set('display_errors', '1');

<?php
session_start();

    include("connection.php");
    include("functions.php");

 
// Check connection
if($con === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
if(isset($_POST['d_name'])){
if(isset($_POST['manner_death'])){
if(isset($_POST['place_death'])){
if(isset($_POST['nok'])){
if(isset($_POST['rel_nok'])){
if(isset($_POST['morgue_att'])){
if(isset($_POST['tag_num'])){
if(isset($_POST['treatment']))

 
// Escape user inputs for security
$d_name = mysqli_real_escape_string($con, $_REQUEST['d_name']);
$manner_death = mysqli_real_escape_string($con, $_REQUEST['manner_death']);
$place_death = mysqli_real_escape_string($con, $_REQUEST['place_death']);
$nok = mysqli_real_escape_string($con, $_REQUEST['nok']);
$rel_nok = mysqli_real_escape_string($con, $_REQUEST['rel_nok']);
$morgue_att = mysqli_real_escape_string($con, $_REQUEST['morgue_att']);
$tag_num = mysqli_real_escape_string($con, $_REQUEST['tag_num']);
$treatment = mysqli_real_escape_string($con, $_REQUEST['treatment']);
 
// Attempt insert query execution

$sql = "INSERT INTO data (d_name, manner_death, place_death, nok, rel_nok, morgue_att, tag_num, treatment) VALUES ('$d_name', '$manner_death', ','$place_death','$nok','$rel_nok', '$morgue_att','$tag_num','$treatment')";
}else

if(mysqli_query($con, $sql)){
    echo "Records added successfully.";
}
    
 {
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($con);

 
// Close connection
mysqli_close($con);
}
?> 
 

Link to comment
Share on other sites

6 hours ago, simbae said:

requinix#3344 what would your code look like, im just a novice kindly highlight  my errors

I don't know what my code would look like because I don't know anything about your application.

The first problems to solve are the ones that are quite visibly wrong. Such as how you have a couple lines of PHP code that aren't within the <?php ?> tags. And those crazy if statements ginerjm mentioned. And the syntax error in your INSERT statement.

Link to comment
Share on other sites

requinix#3344 

error_reporting(E_ALL);

        ini_set('display_errors', '1');

i have tried troubleshooting the errors are fewer what needs to be done now

<?php
?><?php
session_start();

    include("connection.php");
    include("functions.php");
mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);
 
// Check connection
if($con === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
if(isset($_POST['d_name'])){
}
if(isset($_POST['manner_death'])){
}
if(isset($_POST['place_death'])){
}
if(isset($_POST['nok'])){
}
if(isset($_POST['rel_nok'])){
}
if(isset($_POST['morgue_att'])){
}
if(isset($_POST['tag_num'])){
if(isset($_POST['treatment']))

 
// Escape user inputs for security
$d_name = mysqli_real_escape_string($con, $_REQUEST['d_name']);
$manner_death = mysqli_real_escape_string($con, $_REQUEST['manner_death']);
$place_death = mysqli_real_escape_string($con, $_REQUEST['place_death']);
$nok = mysqli_real_escape_string($con, $_REQUEST['nok']);
$rel_nok = mysqli_real_escape_string($con, $_REQUEST['rel_nok']);
$morgue_att = mysqli_real_escape_string($con, $_REQUEST['morgue_att']);
$tag_num = mysqli_real_escape_string($con, $_REQUEST['tag_num']);
$treatment = mysqli_real_escape_string($con, $_REQUEST['treatment']);
 
// Attempt insert query execution

$query = "insert into data 
( d_name,   manner_death,   place_death    ,nok,   rel_nok,   morgue_att,  tag_num,  treatment) values 
( '$d_name'.'$manner_death','$place_death','$nok','$rel_nok','$morgue_att','$tag_num','$treatment')"; 
}else

if(mysqli_query($con, $query)){
    echo "Records added successfully.";
}
    
 {
    echo "ERROR: Could not able to execute $query. " . mysqli_error($con);
 }
 
// Close connection
mysqli_close($con);
?>  
 

 

Link to comment
Share on other sites

You've fixed things but you haven't fixed things. Like these:

if(isset($_POST['d_name'])){
}
if(isset($_POST['manner_death'])){
}
if(isset($_POST['place_death'])){
}
if(isset($_POST['nok'])){
}
if(isset($_POST['rel_nok'])){
}
if(isset($_POST['morgue_att'])){
}

What are those doing? Nothing. They don't do anything. Then you have

if(isset($_POST['tag_num'])){
if(isset($_POST['treatment']))

The first line makes sense, but the second? Without a pair of { } then it will only run the very first line of code that comes after: the assignment for $d_name.

Then in your query,

$query = "insert into data 
( d_name,   manner_death,   place_death    ,nok,   rel_nok,   morgue_att,  tag_num,  treatment) values 
( '$d_name'.'$manner_death','$place_death','$nok','$rel_nok','$morgue_att','$tag_num','$treatment')"; 

you managed to fix the one syntax error but you created a new one.

 

You cannot create websites by putting code in your editor and hoping everything will work. You have to make actual, conscious, deliberate decisions about the code. You have to know what different pieces of code mean. You have to understand why code is what it is and then how you can use it to accomplish what you want.

So before you try to write more code, stop and take a few days to learn what you can about PHP. Then come back to this file and put some thought into each line of code in it.

  • Thanks 1
  • Great Answer 1
Link to comment
Share on other sites

here's an outline of what the code you are showing us should/should-not do -

  1. put any php error_reporting and display_errors settings in the php.ini on your system. this will let you make changes to these settings in one place and simplify your code.
  2. use 'require', not 'include', for things that your code must have for it to work. also, require/include are not functions and the () around the filename are not needed, simplifying your code.
  3. don't write code that isn't being used. in the current code, there are no session variables nor any user written functions. remove the session_start() and include("functions.php"); line, i.e. keep your code simple and uncluttered.
  4. the mysqli_report(...) statement should be before the point where you make the database connection, which you were also told in a previous thread on this forum.
  5. because the mysqli_report(...) statement causes the connection, query, prepare, and execute database statements to use exceptions for errors, the error handling logic you have now won't ever be executed upon an error, and should be removed, simplifying your code.
  6. the post method form processing code should detect if a post method form was submitted before referencing any of the form data. in your previous thread on this forum, you were doing this. why have you now changed from a simple statement to the mess of if()/isset() ... statements and why are you now using both $_POST and $_REQUEST variables? just use $_POST if you expect the data to be from a post method form.
  7. keep the input data as an array and operate on elements of this array throughout the rest of the code, i.e. don't write out line after line of code needlessly copying variables to other variables, simplifying your code.
  8. the post method form processing code should trim, then validate all the inputs, storing user/validation error messages in an array using the field name as the array index.
  9. after all the validation logic, if there are no errors (the array holding the user/validation error messages will be empty), use the submitted form data. if there are errors, you would display the contents of the errors array when you re-display the form.
  10. also in that previous thread, member(s) stated to use a prepared query to safely supply data to a query and to use the (much simpler) PDO extension. a prepared query, provided you use the PDO extension, only adds one php statement per query, allows you to eliminate any _escape_string() statements, and simplifies your sql query syntax, helping to prevent mistakes.
  11. after successfully completing all the post method form processing code, you should redirect to the exact same url of the current page to cause a get request for the page. this will prevent the browser from trying to re-submit the form data if the user reloads the page or browses back to the url of the page.
  12. in most cases, there's no need to close database connections, free query results, or free prepared query statements, since php will destroy all resources used on a page when your script ends, simplifying your code. 

you will notice a theme in the above of simplifying the code/query. there's a lot of old information to be found in books, course material, and on the web that is no longer needed.

the following is a pseudo code example showing these points -

<?php

// use the much simpler PDO extension
require 'pdo_connection.php';

$post = []; // an array to hold a trimmed working copy of the form data
$errors = []; // an array to hold user/validation error messages

// post method form processing
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	// trim all the form data at once (if any of the form fields are arrays, write and use a recursive trim function here instead of php's trim)
	$post = array_map('trim',$_POST);
	
	// validate the inputs here...
	
	// if no errors, use the form data
	if(empty($errors))
	{
		// build the sql query statement, using a prepared query
		$query = " the sql query "; 
		
		// prepare and execute the query
		// note: the following uses the PDO extension
		$stmt = $pdo->prepare($query);
		$stmt->execute([ an array of the input values ]);
		
		// note: an insert/update query may result in duplicate data. if this is an error condition
		// for your application you would define an appropriate unique index for your database table
		// then you would have exception try/catch logic for this query to detect if a duplicate
		// error number occurred and setup and display a message (add it to the $errors array)
		// telling the user what was wrong with the data that they submitted. for all other error
		// numbers just re-throw the exception and let php handle it
	}

	// if no errors, success
	if(empty($errors))
	{
		// redirect to the exact same url of this page to cause a get request - Post, Redirect, Get (PRG.)
		header("Refresh:0");
		die;
	}
}
?>


<?php
// at the appropriate point in the html document, test and display any errors
if(!empty($errors))
{
	echo implode('<br>',$errors);
}
?>

<?php
// you would re-populate the form field values with any existing data so that the user doesn't need to keep reentering things over and over
?>

 

Link to comment
Share on other sites

It should be noted that trimming $_POST with array_map as shown will fail on multi-dimensional arrays. A simple function will solve the problem.

 

function trim_array($input)
{
    if (!is_array($input))
    {
        return trim($input);
    }
    return array_map('trim_array', $input);
}

$_POST = [
    ["data1 ", "     data2", "  data3  "],
    ["data4", " data5", "    data6       "]];

$post = trim_array($_POST);
var_dump($post);

 

Link to comment
Share on other sites

I'm pretty new to PHP too and I'm not sure if you've figured out some of you issues yet, but in the spirit of trying to contribute more I'll add my two cents.

All those if(isset) statements should be filtered down to one if(isset) that refers to - think of the form element that submits data -  and then try to assign your variables within.

happy learning

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • 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.