Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8198701
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T06:00:22+00:00 2026-06-07T06:00:22+00:00

I’m new to PHP and MySQL query construction. I asked a similar question yesterday

  • 0

I’m new to PHP and MySQL query construction. I asked a similar question yesterday about columns, and now need help with VALUES. I have a processor for a large form. A few fields are required, most fields are user optional. In my case, the HTML ids and the MySQL column names are identical. I’ve found tutorials about using arrays to convert $_POST into the fields and values for INSERT INTO, but I can’t get them working – after many hours. I’ve stepped back to make a very simple INSERT using arrays and variables, but I’m still stumped. The following lines work and INSERT the values of 5 variables into a database with over 100 columns. The first 4 items are strings, the 5th item, monthlyRental is an integer.

$colsx = array('country', 'stateProvince', 'city3', 'city3Geocode', 'monthlyRental');
$col_string = implode(',', $colsx);
$query = "INSERT INTO `$table` ($col_string) VALUES ( '$country', '$stateProvince', '$city3', '$city3Geocode', '$monthlyRental')";

Following this idea, I use pre-processed variables to construct an array and then implode it to create a string.

//these variables are "pre-processed", e.g., $country=$_POST['country'] and validated, but not yet mysql_real_escape_string
$valsx = array( '$country',  '$stateProvince', '$city3', '$city3Geocode', '$monthlyRental' );
$val_string = implode(",", $valsx);
$query = "INSERT INTO `$table` ($col_string) VALUES ( $val_string )";

It does not work. I’ve tried changing a lot of things, but with no results. The MySQL error that I get with this code is – Unknown column ‘$country’ in ‘field list’ It is referring to ‘$country’ in the $valsx array, but I don’t see how this is a field list, or how to fix the problem.

Please be specific with suggestions. I’m pretty new at MySQL and PHP.

OK, with Iserni’s suggestions, here’s the current code. It does not execute. I need help with his code, and I need help with where and how to put error messages.

$colsx = $fields = $valsx = $values = array();
$colsx = array('country', 'stateProvince', 'city3', 'city3Geocode', 'monthlyRental');
$col_string = implode(',', $colsx);
$valsx = array( "$country",  "$stateProvince", "$city3", "$city3Geocode", "$monthlyRental" );
$val_string = implode(",", $valsx);
foreach($colsx as $col) {
    $fields[] = $col;
    if ( is_numeric($_POST[$col]) ) {
        $values[] = mysql_real_escape_string($_POST[$col]);
    }else{
        $values[] = "'".mysql_real_escape_string($_POST[$col])."'";
    }
}
$fields_sql = implode(',', $fields);
$values_sql = implode(',', $values);
$query = "INSERT INTO `$table` ($fields_sql) VALUES ($values_sql);"
if (!mysql_query($query,$conn))
{
    die('<li class=error>an error occurred posting to the database. </li>'. mysql_error());
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T06:00:23+00:00Added an answer on June 7, 2026 at 6:00 am

    I’d do like this:

    $colsx = array('country', 'stateProvince', 'city3', 'city3Geocode', 'monthlyRental');
    // List of optional fields
    $colsy = array('otherfield', 'other2', ...);
    
    // Building the query
    $fields = array();
    $values = array();
    
    // Mandatory fields
    foreach($colsx as $col)
    {
        if (!isset($_POST[$col]))
            die("MISSING field $col";
        $fields[] = $col;
        if (is_numeric($_POST[$col]))
            $values[] = mysql_real_escape_string($_POST[$col]);
        else
            $values[] = "'".mysql_real_escape_string($_POST[$col])."'";
    }
    
    // Optional fields
    foreach($colsy as $col)
    {
        //if (!isset($_POST[$col]))
        //    die("MISSING field $col";
        $fields[] = $col;
        if (is_numeric($_POST[$col]))
            $values[] = mysql_real_escape_string($_POST[$col]);
        else
            $values[] = "'".mysql_real_escape_string($_POST[$col])."'";
    }
    
    $fields_sql = implode(',', $fields);
    $values_sql = implode(',', $values);
    
    $query = "INSERT INTO `$table` ($fields_sql) VALUES ($values_sql);"
    

    If you already have the validated fields, you can do it this way (but then it would be better, as I saw someone suggest, to use PDO instead of mysql_ functions; consider doing this later on).

    $data = array(
        // FIELD            VALUE ("$country" and $country are the same thing)
        'country'        => $country,
        'stateProvince'  => $stateProvince,
        'city3'          => $city3,
        ...
    );
    
    // If you need to add a field conditionally, you do it like this:
    // if (isset($_POST['newfield']))
    //     $data['newfield'] = $_POST['newfield'];
    // or also, maybe:
    //
    // if (isset($_POST['newfield']) && !empty($_POST['newfield']))
    //     $data['newfield'] = $_POST['newfield'];
    
    // Process the values in $data to get SQL fields (PDO does this by itself)
    
    $values = array();
    foreach($data as $field => $value)
    {
        if (is_numeric($value))
            $values[] = $value;
        else
            $values[] = "'".mysql_real_escape_string($value)."'";
    }
    // Now we have all we need. The "fields" are $data's keys.
    $fields_sql = implode(',', array_keys($data));
    $values_sql = implode(',', $values);
    
    $query = "INSERT INTO `$table` ($fields_sql) VALUES ($values_sql);";
    

    Same thing using PDO:

    $data = array(
        // FIELD            VALUE ("$country" and $country are the same thing)
        'country'        => $country,
        'stateProvince'  => $stateProvince,
        'city3'          => $city3,
        ...
    );
    
    // Process $data to get SQL fields (we could use array_fill)
    $values = array();
    foreach($data as $field => $value)
        $values[] = '?'; // Placeholder, without quotes
    
    $fields_pdo = implode(',', array_keys($data));
    $values_pdo = implode(',', $data);
    
    // This is now INSERT INTO mytable (city,rent,...) VALUES (?,?,?,...);
    $query = "INSERT INTO $table ($fields_sql) VALUES ($values_sql);";
    
    $q = $conn->prepare($query);
    $q->execute(array_values($data));
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I don't have much knowledge about the IPv6 protocol, so sorry if the question
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I would like to count the length of a string with PHP. The string
I am reading a book about Javascript and jQuery and using one of the
I want use html5's new tag to play a wav file (currently only supported

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.