mysql数据库二个数据表字段内容如何同步?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql数据库二个数据表字段内容如何同步?相关的知识,希望对你有一定的参考价值。

请问同一数据库内的2个表例如A表的a字段和B表的b字段的内容如何实现时时同步!

都是一个数据库里,直接用关联即可,
1。这样即可以省数据库空间,
2。还方便数据操作,
3。并且不要做二次数据插入!
4。而且绝对的同步!
参考技术A 用促发器就可以啦 参考技术B 设置外键关联,行不

使用 PHP、AJAX 和 MySQL 选择下拉列表选项后,如何显示数据库内容?

【中文标题】使用 PHP、AJAX 和 MySQL 选择下拉列表选项后,如何显示数据库内容?【英文标题】:How can I display DB contents after selecting a dropdown list option using PHP, AJAX and MySQL? 【发布时间】:2011-11-29 04:44:26 【问题描述】:

我是 AJAX 新手,想用两个下拉框创建一些东西。当用户选择第一个时,第二个下拉列表会填充相应的字段。从第二个下拉列表中选择一个选项后,我想要一个表格来显示数据库中与选择相对应的所有信息。我在网上找到了一个示例,但无法修改它。我只能显示一个字段。这是代码:

ajax_select

//function used to remove the next lists already displayed when it chooses other options
    function removeLists(colid) 
  var z = 0;
  // removes data in elements with the id stored in the "ar_cols" variable
  // starting with the element with the id value passed in colid
  for(var i=1; i<ar_cols.length; i++) 
    if(ar_cols[i]==null) continue;
    if(ar_cols[i]==colid) z = 1;
    if(z==1) document.getElementById(preid+ar_cols[i]).innerHTML = '';
  


// create the XMLHttpRequest object, according browser
function get_XmlHttp() 
  // create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
  var xmlHttp = null;

  if(window.XMLHttpRequest)  xmlHttp = new XMLHttpRequest();      // for Forefox, IE7+, Opera, Safari
  else if(window.ActiveXObject)  xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");       // IE5 or 6

  return xmlHttp;


// sends data to a php file, via POST, and displays the received answer
function ajaxReq(col, wval) 
  removeLists(col);           // removes the already next selects displayed

  // if the value of wval is not '- - -' and '' (the first option)
  if(wval!='- - -' && wval!='') 
    var request =  get_XmlHttp();             // call the function with the XMLHttpRequest instance
    var php_file = 'select_list.php';     // path and name of the php file

    // create pairs index=value with data that must be sent to server
    var  data_send = 'col='+col+'&wval='+wval;

    request.open("POST", php_file, true);           // set the request

    document.getElementById(preid+col).innerHTML = 'Loadding...';   // display a loading notification

    // adds a header to tell the PHP script to recognize the data as is sent via POST
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send(data_send);            // calls the send() method with data_send

    // Check request status
    // If the response is received completely, will be added into the tag with id value of "col"
    request.onreadystatechange = function() 
      if (request.readyState==4) 
        document.getElementById(preid+col).innerHTML = request.responseText;
      
    
  

selected_list.php

    <?php
    // Multiple select lists - www.coursesweb.net/ajax/
    if(!isset($_SESSION)) session_start();

    // Here add your own data for connecting to MySQL database
    $server = 'localhost';
    $user = 'root';
    $pass = '***';
    $dbase = '**';

    // Here add the name of the table and columns that will be used for select lists, in their order
    // Add null for 'links' if you don`t want to display their data too
    $table = 'cpu_table';
    $ar_cols = array('endor', 'ype', 'name');

    $preid = 'slo_';        // a prefix used for element's ID, in which Ajax will add <select>
    $col = $ar_cols[0];     // the variable used for the column that wil be selected
    $re_html = '';          // will store the returned html code

    // if there is data sent via POST, with index 'col' and 'wval'
    if(isset($_POST['col']) && isset($_POST['wval'])) 
      // set the $col that will be selected and the value for WHERE (delete tags and external spaces in $_POST)
      $col = trim(strip_tags($_POST['col']));
      $wval = "'".trim(strip_tags($_POST['wval']))."'";
    

    $key = array_search($col, $ar_cols);            // get the key associated with the value of $col in $ar_cols
    $wcol = $key===0 ? $col : $ar_cols[$key-1];     // gets the column for the WHERE clause
    $_SESSION['ar_cols'][$wcol] = isset($wval) ? $wval : $wcol;    // store in SESSION the column and its value for WHERE

    // gets the next element in $ar_cols (needed in the onchange() function in <select> tag)
    $last_key = count($ar_cols)-1;
    $next_col = $key<$last_key ? $ar_cols[$key+1] : '';

    $conn = new mysqli($server, $user, $pass, $dbase);     // connect to the MySQL database

    if (mysqli_connect_errno())  exit('Connect failed: '. mysqli_connect_error());      // check connection

    // sets an array with data of the WHERE condition (column=value) for SELECT query
    for($i=1; $i<=$key; $i++) 
      $ar_where[] = '`'.$ar_cols[$i-1].'`='.$_SESSION['ar_cols'][$ar_cols[$i-1]];
    

    // define a string with the WHERE condition, and then the SELECT query
    $where = isset($ar_where) ? ' WHERE '. implode($ar_where, ' AND ') : '';
    $sql = "SELECT DISTINCT `$col` FROM `$table`".$where;

    $result = $conn->query($sql);       // perform the query and store the result

    // if the $result contains at least one row
    if ($result->num_rows > 0) 
      // sets the "onchange" event, which is added in <select> tag
      $onchg = $next_col!==null ? " onchange=\"ajaxReq('$next_col', this.value);\"" : '';

      // sets the select tag list (and the first <option>), if it's not the last column
      if($col!=$ar_cols[$last_key]) $re_html = $col. ': <select name="'. $col. '"'. $onchg. '><option>- - -</option>';

      while($row = $result->fetch_assoc()) 
        // if its the last column, reurns its data, else, adds data in OPTION tags
        if($col==$ar_cols[$last_key]) $re_html .= '<br/>'. $row[$col];
        else $re_html .= '<option value="'. $row[$col]. '">'. $row[$col]. '</option>';
      

      if($col!=$ar_cols[$last_key]) $re_html .= '</select> ';        // ends the Select list
    
    else  $re_html = '0 results'; 

    $conn->close();

    // if the selected column, $col, is the first column in $ar_cols
    if($col==$ar_cols[0]) 
      // adds html code with SPAN (or DIV for last item) where Ajax will add the select dropdown lists
      // with ID in each SPAN, according to the columns added in $ar_cols
      for($i=1; $i<count($ar_cols); $i++) 
        if($ar_cols[$i]===null) continue;
        if($i==$last_key) $re_html .= '<div id="'. $preid.$ar_cols[$i]. '"> </div>';
        else $re_html .= '<span id="'. $preid.$ar_cols[$i]. '"> </span>';
      

      // adds the columns in JS (used in removeLists() to remove the next displayed lists when makes other selects)
      $re_html .= '<script type="text/javascript">var ar_cols = '.json_encode($ar_cols).'; var preid = "'. $preid. '";</script>';
    
    else echo $re_html;
    ?>

有没有更简单的方法来实现这一点?

谢谢

【问题讨论】:

我想说一种更简单的方法是使用 jQuery 来捕获用户与更改事件和 ajax 请求的交互。两者都有很好的记录:-api.jquery.com/changeapi.jquery.com/jQuery.ajax 您的代码中有一个 SQL 注入漏洞。 不要使用strip_tags 转义SQL 参数。请改用mysqli_real_escape_string。并且不要费心转义表或列名,这是没用的,只需确保将它们列入白名单,就像在代码中正确完成的那样。 【参考方案1】:

这是我用来在下拉列表中获取数据库内容的方法。

<?php 
mysql_connect('localhost','username','password');
mysql_select_db('databasename');
$query = mysql_query("SELECT columname FROM tablename");

echo '<select name="name">';
while ($row = mysql_fetch_array($query)) 
echo '<option value="'.$row['columname'].'">'.$row['columname'].'</option>';


echo '</select>';
?>

(我知道 mysql_ 不再是这种方式了,但这对我有用)希望这也对你有用

【讨论】:

以上是关于mysql数据库二个数据表字段内容如何同步?的主要内容,如果未能解决你的问题,请参考以下文章

如何将clickhouse的数据同步到mysql?

多个MYSQL表,如何批量查询数据

elasticsearch与mysql数据同步多个表(logstash)

如何将来自三个 Perl 数组的数据插入到单个 MySQL 表中?

如何使用AJAX在java中显示MYSQL的数据

线上环境mysql主从同步的搭建过程