[英]Can not write to MySQL-DB with PHP triggered by JQuery
你好,有溢出!
我是在这里提出问题的新手,但是我在这里已经读了很多东西,这已经对我有所帮助。 这次虽然我遇到了一个问题,但似乎找不到该线程或解决方案。
因此发生了以下情况:
我有一个前端,人们可以通过单击按钮来更改设计以使用。 那确实很好。 但是它应该将主题名称保存到数据库。 它说可以,但是不能-如果使用JS / JQuery在网站上触发了该保存操作。 但是,如果我使用PHP文件手动触发它,它确实可以:
./lib/savetheme.php?user=用户名&theme =主题名称
如果我通过JS触发它,它将通过php,这实际上会回显所需的TRUE。 但是它不会保存到数据库。 它不会引发任何错误(它会死掉-但它会呼应true ..)。
所以代码来了...
common.php
<?php
function m($str) {
$str = mysql_escape_string($str);
return "'".$str."'";
}
?>
db-connect-data.php
<?php
$dbname = "dbname";
$dbuser = "dbuser";
$dbpw = "dbpw";
$dbhost = "localhost";
$dbport = "3306";
?>
db-connect.php
<?php
if (!mysql_connect($dbhost.":".$dbport, $dbuser, $dbpw)) {
die();
}
if (!mysql_select_db($dbname)) {
die();
}
?>
savetheme.php
require "./common.php";
require "./db-connect-data.php";
require "./db-connect.php";
if(isset($_GET)) {
$user = "";
$theme = "";
if($_GET['user'] != "") {
$user = $_GET['user'];
}
if($_GET['theme'] != "") {
$theme = $_GET['theme'];
}
$sql = "UPDATE users SET
theme = ".m($theme)."
WHERE username = ".m($user);
if(mysql_query($sql)) {
echo "TRUE";
} else {
echo mysql_error();
}
}
?>
profile.php
<?php
foreach (glob("./themes/*",GLOB_ONLYDIR) as $file) {
$output = str_replace("./themes/", "", $file);
echo '<button class="buttons themebuttons" id="'
.$output.'">'.$output.'</button>';
}
?>
<div class="ui-widget" id="savethemeok">
<br>
<div class="ui-state-green ui-corner-all">
<p>
Theme saved successfully!
</p>
</div>
</div>
<div class="ui-widget" id="savethemeerror">
<br>
<div class="ui-state-red ui-corner-all">
<p>
Error! Theme could not be saved!
</p>
</div>
</div>
main.js
$(document).ready(function() {
$(".buttons").button();
$(".themebuttons").click(function() {
var themename = $(this).attr("id");
var themepath = "./themes/" + themename + "/jquery-ui.css";
console.log("Saving new theme...");
$.get( "./lib/savetheme.php" , {
user: $("#loggeduser").attr("value"),
theme: "'" + themename + "'",
}, function(status) {
if(status == "TRUE") {
console.log("New theme: " + themename);
$("#theme").attr({href: themepath});
$("#savethemeok").show();
window.setTimeout(function() {
$("#savethemeok").fadeOut();
}, 2500);
} else {
console.log("Error: " + status);
$("#savethemeerror").show();
window.setTimeout(function() {
$("#savethemeerror").fadeOut();
}, 2500);
}
});
});
});
还有更多的代码,我希望我能得到所有相关的代码,但是如果我复制了几乎不涉及此特定问题的近1000行代码,我认为这将不会再引起人们的注意。 如果需要,我会做。
我对任何建议都感到高兴和感谢,因为我已经花了一些时间解决这个问题,而且似乎我不知道为什么当我通过JS触发它时它不保存到db而是为什么在手动触发时它可以正常工作用PHP ...
对不起,如果有一个关于我错过的地方有这个话题。 如果有,请告诉我。 我什么也没找到。 再说一次,也许我太愚蠢以至于找不到它,我确实在用语言表达我的问题上有点挣扎...
谢谢大家!
问题已解决。
我已经将用户变量更改为另一个用户-因此自然没有将其保存到我正在查看的用户。
抱歉通知您。
感谢您的观看-并以Robin Robins的荣誉:CARPE DIEM。
根据您在问题中发布的内容,您的列theme
和username
似乎是varchar
类型。 尝试将查询修改为以下内容:
$sql = "UPDATE users SET theme = '".m($theme)."' WHERE username = '".m($user)."'";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.