简体   繁体   English

如何使用php ajax和mysql动态更改内容

[英]How to dynamically change content with php ajax and mysql

I have created a page that populates a sidebar with links(categories) using a database table. 我创建了一个页面,该页面使用数据库表使用链接(类别)填充侧栏。 The table contains names(names of the categories) and their ids. 该表包含名称(类别名称)及其ID。

     e.g 
           | **id** |**name**|
           |  1     |  Men   |
           |  2     |  Women |

I need to do the following things: 我需要做以下事情:

  • When a link is clicked, a corresponding h1 tag changes it's value to the name of the link(the category name). 单击链接后,相应的h1标记会将其值更改为链接的名称(类别名称)。
  • A div tag, that displays product images below the h1 tag, also changes. 在h1标签下方显示产品图片的div标签也会更改。 I have created a table to hold product data. 我创建了一个表来保存产品数据。 It contains the following data fields: 它包含以下数据字段:

      **id**(id for the product)-INT[PRIMARY KEY] **category_id**(category id)-INT[FOREIGN KEY] **name**(product name)-VARCHAR **image**(image file name eg "blu_dress.png" ) eg | **id** |**categoty_id**| **name** | **image** | | 1 | 2 |black blouse |bla_blouse.png| | 2 | 2 | blue dress | blu_dress.png| | 3 | 1 | brown shirt | bro_shirt.png| | 4 | 2 | blue blouse |blu_blouse.png| 

PHP CODE TO POPULATE SIDEBAR PHP代码可增加边栏

    <?php 
$dynamicList = "";

$sql = mysql_query("SELECT * FROM categories ORDER BY id ASC");

$productCount = mysql_num_rows($sql); // count the output amount

if ($productCount > 0) 
{
    while($row = mysql_fetch_array($sql)){ 
             $id = $row["id"];
             $category_name = $row["name"];
             $sql2 = mysql_query("SELECT * FROM categories WHERE id='".$id."'");
             $dynamicList .= '

                <li id="categegoryLink">
                    <a href="category.php?ID="'$category_name.'"" onclick="">   
                         '.$category_name.'
                    </a>
                </li>

                ';
    }
} 
else 
{
    $dynamicList = "We have no categories listed in our store yet";
}
mysql_close();
?> 

AJAX CODE AJAX代码

<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("title").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","category.php",true);
xmlhttp.send();
}
</script>

category.php category.php

<?php echo $category_id?>

FURTHER INFO I can't post images since I don't have the reputation but I have an image that explains what I need further, if you need it. 更多信息因为我没有声誉,所以我无法发布图片,但是如果您需要,我有一张可以进一步说明我需要的图片。

I'll recommend using jQuery and for database use PDO instead of using mysql . 我建议使用jQuery ,对于数据库,请使用PDO而不是mysql The populated sidebar data is displayed as a list. 填充的侧边栏数据显示为列表。

$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);

$db = new PDO('mysql:host=localhost;dbname=data','root', 'passwd', $options);
$sql = $db->query("SELECT * FROM categories ORDER BY id ASC"); // you can also use prepared statement.
 // displaying categories 
<ul id="category">
   <?php foreach ($sql as $category) : ?>
      <li data-id="<?php echo $category['category_id']; ?>"><?php echo $category['name']; ?></li>
   <?php endforeach; ?>
 </ul>
 <div id="results"></div>

And in your jQuery check for the clicked list item 然后在您的jQuery检查单击的列表项

$("#category li").click(function() {
           var id = $(this).data('id');
          $.post('get.php',{category_id:id},function(data){
              $('#results').html(data);
          });
     }); 

the code for the get.php file get.php文件的代码

<?php
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);

$db = new PDO('mysql:host=localhost;dbname=data','root', 'passwd', $options);
$sql = $db->query("SELECT * FROM categories ORDER BY id ASC"); // you can also use prepared statement.
 if(isset($_POST['category_id'])){
$id = $_POST['id'];
$category = $db-query("SELECT * FROM categories WHERE id = $id");
}
 ?>
  <h1><?php    echo $category['name']; ?></h1>

    <!--display the results of the query here-->

Here when the user clicks any of the list items jQuery will get the value of the data-id attribute 0f which is the id of the category, post this value to get.php file and select data from the database based on id of the category. 在这里,当用户单击任何列表项时, jQuery将获得data-id属性0f的值(即类别的ID),将该值发布到get.php文件,然后根据类别的ID从数据库中选择数据。 And return results form the database. 并从数据库返回结果。 The returned data is appended to the div with id results . 返回的数据将附加到具有id results的div上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM