dqenv99518 2016-04-12 06:17
浏览 58
已采纳

如何使用PHP和AJAX插入SQL? [关闭]

I have looked at this post: Inserting into MySQL from PHP (jQuery/AJAX) but I didn't get the code to work. It's a quite old post so it might not work anymore?

I want to insert a post from my website (PHP) into my database (MySQL) without updating the page. I'm looking at AJAX (for example the link above) but I don't understand how to get it to work.

I have also looked at this video: https://www.youtube.com/watch?v=lwo4fAqaVFM for loading data and that's very simple so I thought it would be as simple to insert, but it wasn't...

Can anyone help me?

This new save.php actually works.

index.php

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="jquery.js"></script>
</head> 

<body>
    <form id="example" method="post">
        <input name="textbox">
        <input type="button" name="submitbuttonname" value="submit" onClick="$.post('save.php', $('form#example').serialize())">
    </form>
</body>

New save.php

$db = new mysqli('localhost','root','','audf');
mysqli_set_charset($db, 'utf8') or die('Charset kunde inte ändras till UTF-8');

if($db->connect_errno){
    die('Sorry, we are having some problems.');
}
$firstName = $_POST["firstName"];

$db->query("INSERT INTO test_db (first_name) VALUES ('".$firstName."')");

Old save.php

$db = new mysqli('localhost','root','','audf');
mysqli_set_charset($db, 'utf8') or die('Charset kunde inte ändras till UTF-8');

if($db->connect_errno){
    die('Sorry, we are having some problems.');
}

if($_POST["submitbuttonname"]) {
    $q = $db->prepare("INSERT INTO test_db (first_name) VALUES (?)");
    $q->execute(array($_POST["textbox"]));
}
  • 写回答

3条回答 默认 最新

  • doulandai0641 2016-04-12 08:47
    关注

    Your form is sending the data as $_GET;
    Add method="POST" to your <form> element.

    edit: Oh. OK I didn't fully read your code:

    Your form is probably being sent before it fires the $.post request.
    Try changing the input type from "submit" to "button".

    Regards ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab