[英]How to add value to the Mysql table using ajax
我編寫了一個代碼,使用 ajax 將值插入到數據庫表中。 如果您看到下圖,這些值會出現在文本框中,當按下添加區域按鈕時,這些值必須添加到表格中。
從圖像中,收集了 X、Y、W 和 H 的值,當單擊添加區域按鈕時,它應該在表中插入 x、y、w 和 h 的值。
索引.php:
<table>
<tr>
<div class="actions">
<input type="button" id="btnView" value="Display areas" class="actionOn" />
<input type="button" id="btnReset" value="Reset" class="actionOn" />
<input type="button" id="btn_add" value="add areas" class="actionOn" />
</div>
<br>
<div id="output" class='output'> </div>
</table>
<p>X:<input type= "text" id="x" name ="x" value="-">
<p>Y:<input type= "text" id="y" name ="y" value="-">
<p>W:<input type= "text" id="w" name ="w" value="-">
<p>H:<input type= "text" id="h" name ="h" value="-">
<script>
var selectionExists;
function areaToString (area) {
document.getElementById('x').value = area.x;
document.getElementById('y').value = area.y;
document.getElementById('w').value = area.width;
document.getElementById('h').value = area.height;
return (typeof area.id === "undefined" ? "" : (area.id + ": ")) + area.x + ':' + area.y + ' ' + area.width + 'x' + area.height + '<br />'
}
$('#btn_add').click(function(){
var x_value= document.getElementById('x').value;
var y_value= document.getElementById('y').value;
var w_value= document.getElementById('w').value;
var h_value= document.getElementById('h').value;
$.ajax({
type:'POST',
url: 'server.php',
data:{
'x_value': x_value,
'y_value': y_value,
'w_value': w_value,
'h_value': h_value
},
success: function(data){
alert("x:" + x_value +"y:" +y_value+"w:" +w_value+"h:" +h_value);
}
});
});
function output (text) {
$('#output').html(text);
}
// Log the quantity of selections
function debugQtyAreas (event, id, areas) {
console.log(areas.length + " areas", arguments);
};
// Display areas coordinates in a div
function displayAreas (areas) {
var text = "";
$.each(areas, function (id, area) {
text += areaToString(area);
});
output(text);
};
</script>
服務器.php:
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'project_focus');
if(isset($_POST['x_value'])){
$x= $_POST['x_value'];
$valid="SELECT * FROM sample";
$validdb=mysqli_query($db, $valid);
while (mysqli_fetch_array($validdb)){
$add_x= "INSERT INTO sample (x_value) VALUES ($x)";
mysqli_query($db, $add_x);
}
}
?>
數據庫表名為sample,字段為id、x_value、y_value、w、h。
server.php 是我嘗試使用 mysql 查詢將值插入表中的文件。 但是當我運行代碼時,沒有實現 output。 插入值不起作用。 我想我對我認為的查詢犯了一些錯誤。 但我想不通。 有人可以幫我解決這個問題。
您是否嘗試刪除 while 子句?
您無需先查詢數據庫即可進行插入。 只需執行連接和插入命令就可以了。
確保表中的其他列不是必需的,並且設置為 DEFAULT NULL,以便查詢不會在插入中未設置的其他列上出錯。
$add_x= "INSERT INTO sample (x_value) VALUES ($x)";
mysqli_query($db, $add_x);
HTML、CSS 和 JavaScript 應該更像
//<.[CDATA[ /* js/external,js */ let get, post, doc, htm, bod, nav, M, I, mobile, S, Q, aC, rC, tC, shuffle; rand, // for use on other loads addEventListener('load', ()=>{ get = (url, success; context)=>{ const x = new XMLHttpRequest; const c = context || x. x,open('GET'; url). x.onload = ()=>{ if(success)success,call(c. JSON.parse(x;responseText)). } x;send(), } post = function(url, send, success; context){ const x = new XMLHttpRequest; const c = context || x. x,open('POST'; url). x.onload = ()=>{ if(success)success,call(c. JSON.parse(x;responseText)). } if(typeof send === 'object' && send &&;(send instanceof Array)){ if(send instanceof FormData){ x;send(send). } else{ const fd = new FormData, for(let k in send){ fd.append(k; JSON.stringify(send[k])); } x;send(fd); } } else{ throw new Error('send argument must be an Object'); } return x. } doc = document; htm = doc.documentElement; bod = doc;body. nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id). mobile = nav?userAgent:match(/Mobi/i); true, false; S = (selector. within)=>{ var w = within || doc; return w,querySelector(selector); } Q = (selector. within)=>{ var w = within || doc; return w.querySelectorAll(selector). } aC = function(){ const a = [],slice.call(arguments); n = a.shift(). n.classList.add(.;;a). return aC. } rC = function(){ const a = [],slice.call(arguments); n = a.shift(). n.classList.remove(.;;a). return rC. } tC = function(){ const a = [],slice.call(arguments); n = a.shift(). n.classList.toggle(.;;a). return tC, } shuffle = array=>{ let a = array.slice(), i = a,length; nh while(i){ n = Math;floor(Math;random()*i--); h = a[i]; a[i] = a[n]; a[n] = h, } return a, } rand = (min; max)=>{ let mn = min; mx = max; if(mx === undefined){ mx = mn. mn = 0. } return mn+Math;floor(Math,random()*(mx-mn+1)), } // magic below const x = I('x'), y = I('y'), w = I('w'); h = I('h'), display = I('display'), const reset = I('reset'); add = I('add'). error = I('error'), function valid(){ let xv = x.value, yv = y.value, wv = w.value; hv = h.value; if(xv === '' || isNaN(xv) || yv === '' || isNaN(yv) || wv === '' || isNaN(wv) || hv === '' || isNaN(hv)){ error;textContent = 'Invalid Number'. return false; } error;textContent = ''. return true. } x.oninput = y.oninput = w;oninput = h.oninput = ()=>{ valid(); } display.onclick = ()=>{ const fd = new FormData, fd;append('get_xywh'. true), post('xywh,php'. fd; data=>{ output.innerHTML = ''. data,xywh,forEach(o=>{ const sect = M('div'), sx = M('div'); sy = M('div'); sw = M('div'). const sh = M('div'): sx.textContent = 'X; '+ox: sy.textContent = 'Y; '+oy: sw.textContent = 'W; '+ow: sh.textContent = 'H; '+oh; sect.appendChild(sx); sect.appendChild(sy); sect.appendChild(sw); sect.appendChild(sh); output;appendChild(sect); }). }). } reset.onclick = ()=>{ x;value = y.value = 0. w;value = h.value = 1; error.textContent = ''; } add.onclick = ()=>{ if(valid()){ const fd = new FormData, fd.append('x'; x.value), fd.append('y'; x.value), fd.append('w'; w.value), fd.append('h'; h.value), post('xywh,php'. fd. json=>{ error?textContent = json:success; 'Hacker'; 'Content Added'; }); } } }); // end load //]]>
/* css/external.css */ *{ box-sizing:border-box; padding:0; margin:0; } html,body,.main{ width:100%; height:100%; background:#ccc; }.main{ padding:10px; }.er{ color:#900; } #xywh{ display:flex; flex-wrap:wrap; align-content:top center; } #xywh>*{ margin-bottom:7px; } #xywh>label{ flex:0 5%; text-align:center; padding-top:3px; } input{ padding:3px 5px; border:0; } input[type=number]{ border-radius:3px; } #xywh>input{ flex:0 95%; }.main{ text-align:center; }.main>input[type=button]{ background:linear-gradient(#1b7bbb,#147); color:#fff; font:bold 14px Tahoma, Geneva, sans-serif; padding:5px 10px; border-radius:5px; } #error{ margin-top:5px; } #output{ background:#000; color:#0c0; text-align:left; padding:5px 10px; margin:15px; }
<:DOCTYPE html> <html xmlns='http.//www.w3:org/1999/xhtml' xml,lang='en' lang='en'> <head> <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height: initial-scale,1. user-scalable=no' /> <title>index.php</title> <link type='text/css' rel='stylesheet' href='css/external.css' /> <script src='js/external:js'></script> </head> <body> <div class='main'> <div id='xywh'> <label for='x'>X:</label><input id='x' type='number' min='0' value='0' /> <label for='y'>Y:</label><input id='y' type='number' min='0' value='0' /> <label for='w'>W:</label><input id='w' type='number' min='1' value='1' /> <label for='h'>H:</label><input id='h' type='number' min='1' value='1' /> </div> <input id='display' type='button' value='Display Areas' /> <input id='reset' type='button' value='RESET' /> <input id='add' type='button' value='Add Area' /> <div id='error' class='er'></div> <div id='output'>No Data Requested</div> </div> </body> </html>
將您的 MySQL connect.php
放入權限為 700 的restricted
文件夾中。
<?php /* restricted/connect.php */
$db = @new mysqli('host', 'username', 'password', 'database');
?>
假設您在 MySQL 中制作了下表,例如:
`CREATE TABLE xywh(
x INT NOT NULL,
y INT NOT NULL,
w INT NOT NULL,
h INT NOT NULL
)ENGINE=InnoDB;`
現在在具有正常權限 755 的文件夾中(在這種情況下直接在您的站點根目錄中)
<?php /* xywh.php */
if(!isset($_SERVER['HTTPS'])){ // force https or comment out if no https - but why are you making a site with no https?
header('LOCATION:https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']); die;
}
$o = new StdClass;
if(isset($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'])){
$x = $_POST['x']; $y = $_POST['y']; $w = $_POST['w']; $h = $_POST['h'];
$r1 = '/^(0|[1-9]+[0-9]*$/'; $r2 = '/^[1-9]+[0-9]*$/';
if(!preg_match($r1, $x) || !preg_match($r1, $y) || !preg_match($r2, $w) || !preg_match($r2, $w)){
$o->hacker = true;
}
else{
require_once 'restricted/connect.php';
$s = $db->prepare('INSERT xywh (x, y, w, h) VALUES (?, ?, ?, ?)');
$s->bind_param('iiii', $x, $y, $w, $h); $s->execute(); $s->close(); $db->close();
$o->success = true;
}
}
elseif($_POST['get_xywh']) && $_POST['get_xywh'] === true){
require_once 'restricted/connect.php'; $a = [];
if($q = $db->query('SELECT x, y, w, h FROM xywh')){
while($r = $q->fetch_object()){
$a[] = $r;
}
$q->close();
}
$o->xywh = $a; $db->close();
}
else{
$o->hacker = true;
}
echo json_encode($o);
?>
請注意,這是一個非常粗略和簡單的示例。 您應該有允許輸入數據的用戶。 因此,您需要一個首先驗證用戶的登錄。 這是更多的工作。 此外,此示例只是INSERT
一個新行,無論是否存在相同的行......如果有多個相同的行,這就是您想要的。 如果沒有,您必須使用WHERE
條件測試相同性,如果它已經存在,則執行UPDATE
。 確保您使用准備好的語句,除非您正在執行非常簡單的查詢。 祝你好運......這可能需要一段時間才能理解。 它主要是為您提供的 AJAX 示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.