My goal is to take data from a MySQL database and then use jquery to load it into divs on the page using the jquery .load() function. I'm new to php, so I'd like to keep it to a minimum and really use jquery to do most of the processing. I can connect to the database, perform a query, and close it, so accessing the database isn't a problem. I'm just not sure what the best way to process that data is. I'm having trouble pulling all these concepts together. Once I get a simple example working, I can go from there.
php to connect to mysql database:
<?php
//connect to database
$dbhost = "yourhost";
$dbuser = "youruser";
$dbpass = "yourpass";
$dbname = "yourdb";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
//Perform database query
$query = "SELECT * ";
$query .= "FROM userInfo ";
$query .= "WHERE ID = 1 ";
$result = mysqli_query($connection, $query);
?>
Code to retrieve the row of data on the user (this is where I need help):
<?php
$user_data = mysqli_fetch_assoc($result)){
//now I want to add more code here to collect all the entries in the row to load into the html.
//Or can I do it in jquery?
}
?>
html:
<div id='ID_number'></div>
<div id='first_name'></div>
<div id='last_name'></div>
close connection:
<?php mysqli_free_result($result); ?>
<?php mysqli_close($connection); ?>
You can use as below :
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode($rows);
In your Html use jquery as below :
$.get( "test.php", function( data ) {
alert( "Data Loaded: " + data );
});
//It return JSON data. parse it in HTML
Here is the good explanation of ajax
Or
If you are not using AJAX :
<?php
while($data = mysqli_fetch_assoc($result)){
echo "<div id='id'>". $data['idfieldname']. "</div>
<div id='fname'>". $data['fname field name']. "</div>
<div id='lname'>". $data['last_name_field_name']. "</div>";
}
?>
<?php
while($user_data = mysqli_fetch_assoc($result)){
echo "<div id='ID_number'>". $user_data['id_field_name']. "</div>
<div id='first_name'>". $user_data['first_name_field_name']. "</div>
<div id='last_name'>". $user_data['last_name_field_name']. "</div>";
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.