gpt4 book ai didi

php - CakePHP 中的 MySQL 连接和查询

转载 作者:行者123 更新时间:2023-11-29 12:31:57 26 4
gpt4 key购买 nike

我在模型文件中使用这些代码,但我认为在 cakePHP 中使用这些 mysql 连接和查询是错误的,当我不使用此代码时,我如何让它工作?

mysql_connect('localhost', 'User', 'pass');
mysql_select_db("database");

mysql_query($import) or die(mysql_error());

这是我的模型文件:

<?php   
mysql_connect('localhost', 'user', 'pass');
mysql_select_db("database");


//$deleterecords = "TRUNCATE TABLE kontaktids"; //empty the table of its current records
//mysql_query($deleterecords);

class Kontaktid extends AppModel {
public $validate = array(
'title' => array(
'rule' => 'notEmpty'
),
'body' => array(
'rule' => 'notEmpty'
)
);
var $name = 'Kontaktid';


function import($filename) {
// to avoid having to tweak the contents of
// $data you should use your db field name as the heading name
// eg: Post.id, Post.title, Post.description
// set the filename to read CSV from
$filename = TMP . 'uploads' . DS . 'Kontaktid' . DS . $filename;

// open the file
$handle = fopen($filename, "r");

// read the 1st row as headings
$header = fgetcsv($handle);

// read each data row in the file

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into kontaktids(id,Eesnimi,Perenimi,Maakond,Linn,Tanav,Maja,Telefon,lisanumbrid) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]')";

mysql_query($import) or die(mysql_error());
}
print "Import done";
// close the file
fclose($handle);

}

}

它运行良好,但我认为使用这些 mysql 查询是错误的

我尝试过类似的方法,但没有成功

$this->query('SELECT * FROM table');

感谢您的帮助!

解决方案

删除

mysql_connect('localhost', 'User', 'pass');
mysql_select_db("database");

mysql_query($import) or die(mysql_error());

并添加这些行

$this->query ("INSERT into kontaktids(id,Eesnimi,Perenimi,Maakond,Linn,Tanav,Maja,Telefon,lisanumbrid) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]')");
$this->query;

最佳答案

你可以去app->config->database.php

class DATABASE_CONFIG {

public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => 'pass',
'database' => 'database',
'prefix' => '',
//'encoding' => 'utf8',
);

}

之后您可以执行此查询`

$this->YourmodelName->query('SELECT * FROM table');

关于php - CakePHP 中的 MySQL 连接和查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27356270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com