0

In the PHP file can anyone help me directly making a for loop where I don't know the number of rows that are going to be selected.

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "mydb";//database details
    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) 
    {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT * FROM mytable";
    $result = $conn->query($sql);
    $myarray = array();
    $index = 0;

    if ($result->num_rows > 0) 
    {
        // output data of each row
        while($row = $result->fetch_assoc()) 
        {
            $myarray[$index] = $row["firstname"];
            $index++;
            $myarray[$index] = $row["lastname"];
            $index++;
            $myarray[$index] = $row["email"];
            $index++;
        }
    } 
    else 
    {
        echo "0 results";
    }
    $conn->close();
?>

The Javascript code contains javascript of a search bar suggestion code and here i didn't mention the typeahead javascript file

var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
        var matches, substringRegex;

        // an array that will be populated with substring matches
        matches = [];

        // regex used to determine if a string contains the substring `q`
        substrRegex = new RegExp(q, 'i');

        // iterate through the pool of strings and for any string that
        // contains the substring `q`, add it to the `matches` array
        $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
                matches.push(str);
            }
        });

        cb(matches);
    };
};

$('#the-basics .typeahead').typeahead({
    hint: true, //here i used typeahead js code though i didnt mentioned here
    highlight: true,
    minLength: 1
}, {
    name: 'states',
    source: substringMatcher(states)
});
1
  • if you don't know the number of rows, you have to make a while loop Commented Feb 1, 2017 at 8:36

2 Answers 2

0

You can simplify the PHP a little bit here when you read in the values as you dont need to increase the index:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details

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

$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $myarray[] =$row["firstname"];
        $myarray[] =$row["lastname"];//storing in the array
        $myarray[] =$row["email"];
    }
} else {
    echo "0 results";
}
$conn->close();
?>

You could echo in the results to the Javascript where you require them, echo($myarray[0]) for example.

Your Javascript may look something like this:

var matches = <?php echo($myarray[0]); ?>
Sign up to request clarification or add additional context in comments.

5 Comments

thanks and can u plz help me how can i connect the php file to the html or js file and i need the php file to run on loading the page and thanks in advance
You can put PHP in with HTML code, just ensure the file is .php
thanks but can u plz tell me how it can be done as i have to do in different files and how do i have to pass the array and if i need to write on same file how should it be done and thank you very much
all i need is to bring that "myarray" in php file to javascript file as soon as the page gets loaded.thanks in advance
var firstname = <?php echo($myarray[0]); ?> will load the firstname into javascript variable, the PHP has to be in the same file as javascript for this
-1

There are 4 ways you can do to insert dynamic content to your javascript code.

  1. Make the javascript inline to your PHP page. That is, putting your js code inside <script> tags

  2. Make the dynamic js variables global and populate them in your php page. Your separate JS files will be able to read these global js variables.

  3. If you want to have a separate file for JS, you have to generate it everytime (because you cant have PHP code in javascript. The browser cannot interpret it, and the server cannot interpret it)
  4. If you want to force the server to interpret PHP code in JS files, add a handler so that .js is handler by the php interpreter (whether php module or php-cgi) see Clean links to PHP-generated JavaScript and CSS

Comments

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.