1

On my webpage I have a number of buttons that relate to table columns in a MySQL database (the id of the buttons and the table column names are exactly the same).

What I would like to do is capture the ids in an array and via AJAX, send back an array of values associated with those table columns with the same names. The AJAX call is no problem, however I'm struggling to understand how to convert the data for use with PHP in my server code.

My code is as follows:

jQuery:

var username = USERNAME;
var array = [1, 2, 3, 4, 5];

$.ajax ({
    cache: false,
    url: PHP_FILE,
    dataType: "json",
    type: "post",
    data: {username: username, array: array},
    success: function(data) {
        console.log(data);
    }
});

PHP:

<?php
    $dbc = DATABASE CONNECTION;

    $username = mysqli_real_escape_string($dbc, trim($_POST['username']));
    $auth = mysqli_real_escape_string($dbc, trim($_POST['array']));

    $array = json_decode($auth, true);

    $query = "SELECT auths.".$array." FROM details INNER JOIN auths USING (code) WHERE un = '".$username."'";
    $data = mysqli_query($dbc, $query);
    $row = mysqli_fetch_array($data);

    echo(json_encode($row));
?>

Presumably json_decode is not the right route, however I'm struggling to understand what the alternative would be.

2
  • try var_dumping $_POST to see what's in it Commented Nov 22, 2013 at 16:05
  • json encode your input array and post over the json'd string instead of an actual array. Commented Nov 22, 2013 at 16:06

3 Answers 3

2

Your JS part needs to be updated

Replace this block:

var $username = USERNAME;
var $array = array(1, 2, 3, 4, 5);

with:

var username = 'USERNAME';
var values = [1, 2, 3, 4, 5];

For the PHP part try with this (assuming you're using PHP >= 5.3):

<?php

$username = trim($_POST['username']);
$fields = isset($_POST['array']) && is_array($_POST['array']) ? $_POST['array'] : array();

$dbc = mysqli_connect ('HOST', 'USERNAME', 'PASSWORD', 'DATABASE', 3306);

$username = mysqli_real_escape_string($dbc, $username);
$fields = array_map(function ($field) use($dbc) {
    $field = mysqli_real_escape_string($dbc, trim($field));
    return 'authors.'.$field;
}, $fields) ;
$fields = implode(',', $fields);
$query = sprintf("SELECT %s FROM details INNER JOIN auths AS authors USING (code) WHERE un = '%s'", $fields, $username);

$rows = array();
if($result = mysqli_query($dbc, $query)) {
    while($row = mysqli_fetch_assoc($result)) {
        $rows[] = $row;
    }
}

echo json_encode($rows);

NOTE: You should apply extra validations assure the username and fields are not empty, as well as receiving incorrect field names as query will throw errors if any of these happens and might expose information about your code and/or database.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. Using this solution, console returns an empty array, which is better than null as I was getting back before, but it's still not quite there. I checked to ensure that the array is being populated prior to AJAX call, which it is, therefore I assume there is a failure somewhere within the PHP script itself?
Ah, I got it: authors should have read auths, the name of the MySQL database. Great answer, works perfectly, thanks so much.
0

JQuery

        var username = USERNAME;
        var array = new Array(1, 2, 3, 4, 5);


        $.ajax ({
            cache: false,
            url: PHP_FILE,
            dataType: "json",
            type: "post",
            data: {username: $username, array:  JSON.stringify(array)},
            success: function(data) {
                console.log(data);
            }
        });

PHP

<?php
    $dbc = DATABASE CONNECTION;

    $username = mysqli_real_escape_string($dbc, trim($_POST['username']));
    $auth = mysqli_real_escape_string($dbc, trim($_POST['array']));

    $array = json_decode($auth, true);

    $query = "SELECT auths.".$array." FROM details INNER JOIN auths USING (code) WHERE un = '".$username."'";
    $data = mysqli_query($dbc, $query);
    $row = mysqli_fetch_array($data);

    echo(json_encode($row));
?>

Comments

0

Can you try this,

        var $username = 'USERNAME';
        var $array = new Array(1, 2, 3, 4, 5);


        $.ajax ({
            cache: false,
            url: PHP_FILE,
            dataType: "json",
            type: "post",
            data: {username: $username, array: $array},
            success: function(data) {
                console.log(data);
            }
        });

2 Comments

If I prefix the variables with a dollar sign in that way, I get a '$username variable not found' error message.
$username = "your username value here";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.