Data from $_POST not added in sql query

Discuss coding issues, and scripts related to PHP and MySQL.
mlucicom
Posts: 37

Data from $_POST not added in sql query

I have this code

Code: Select all

<?php 
session_start();

 $username2=$_SESSION['username'];
require('layout.php');

if (is_array($_POST['data2'])) {
 $media_array2 = $_POST['data2'];

     $checkbox_values2 = ''.implode(',', $media_array2).'';
     echo $checkbox_values2;}
     
// php code -> 1bestcsharp.blogspot.com
// php insert data to mysql database using PDO

if(isset($_POST['submit']))
{
    
    // get values form input text and number

$id = trim($_GET['id']);

    $data = date('m/d/Y');
      $target = "images/";  
      $fileName = $_FILES['Filename']['name'];  
    $fileTarget = $target.$fileName;  
    $tempFileName = $_FILES["Filename"]["tmp_name"];
    $fileDescription = $_POST['Description']; 
    $result = move_uploaded_file($tempFileName,$fileTarget);
    $media_array = $_POST['data'];
     $checkbox_values = ''.implode(',', $media_array).'';

$descriere = $_POST['description'];
  /*
and the mysql insert in database

Code: Select all

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO report (location,probleme,descriere,data,username,zone)
VALUES ('$id', '$checkbox_values','$descriere','$data','$username2','$checkbox_values2')";
echo $sql;
if i echo $checkbox_values2 all work ok.but in sql insert the variable is null

Admin Posts: 805
Hello,
As a general cause: maybe the code with the sql insert query is in another php file, and not included After the $checkbox_values2 variable; or the $checkbox_values2 is not defined Before the sql insert, in the area of same if() statemnent.

- From what it is in your code, the $checkbox_values2 variable is defined when there is $_POST['data2'], not when $_POST['submit']; so, that variable is not defined when there is Not $_POST['data2'].

You have $checkbox_values (without 2) when it is "submit".

mlucicom Posts: 37
The data from $_POST are from a form that is on other page.If i put the "If POST" în the "if submit" the variable is NULL

Admin Posts: 805
The problem is with the script logic. If the $_POST['data2'] not exists when there is "submit", the variable that takes data from $_POST['data2'] will not be defined.
Maybe the solution is to re-think the script logic.
If you apply: var_export($_POST); you will see what $_POST data exists, that you can use in that moment.