如何使用jquery在数据库中创建表

时间:2014-08-02 16:52:24

标签: javascript php jquery mysql ajax

我有一个按钮,按下该按钮将在数据库中创建一个表。 我试过这个

的index.html

<button id="loadButton" type="button" class="btn btn-success" style="margin-top:5px;">Carregar Base de Dados</button>

dash.js

$('#loadButton').click(function() {
    $.ajax({
        url: 'connectdb.php'
    });
});

connectdb.php

<?php

$server = 'localhost';
$user = 'root';
$password = '*****';
$database = 'test';

$con = mysql_connect($server, $user, $password, $database);

if (!$con) {
  die('error: ' . mysql_error($con));
}

// Create table
$sql="CREATE TABLE Post( 
    id_post int Primary Key, 
    titulo varchar(100) not null, 
    imagem longblob,
    descricao varchar(1000) not null,
    hashtag varchar(100) not null
)";

// Execute query
mysql_query($con,$sql))
?>

?>

但是当我检查我的数据库表时没有创建。 我是jquery的新手,我做错了什么。有人能帮助我吗?

3 个答案:

答案 0 :(得分:1)

尝试这个,如果你想要shure,调用php代码用一个简单的echo替换所有代码并检查响应。

$server = 'localhost';
$user = 'root';
$password = '*****';
$database = 'test';

$db = new mysqli($server, $user, $password, $database);

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

$db->query("
CREATE TABLE Post( 
    id_post int Primary Key, 
    titulo varchar(100) not null, 
    imagem longblob,
    descricao varchar(1000) not null,
    hashtag varchar(100) not null
)");

答案 1 :(得分:1)

首先:请使用MySQLi *不推荐使用mysql_ *。

你的.php代码中有错误

mysql_query($con,$sql))
  • ) ))一个;
  • 您的命令末尾应该有$con,$sql
  • 订单错误mysql_query($sql,$con);

这没关系

$database = 'test';
...
$sql="CREATE TABLE test.Post( 

有时您应该在查询中使用数据库'test'

$result = mysql_query($sql,$con);
if (!$result) {
    $message  = 'invalid query: ' . mysql_error() . "\n";
    $message .= 'your query: ' . $sql;
    echo $message;
    die($message);
}

你应该测试你的结果

{{1}}

要搜索错误,这非常有用!

答案 2 :(得分:-1)

直接转到connectdb.php,例如http://www.example.com/connectdb.php,修复所有错误并确保它首先运行。

相关问题