我有一些看起来像这样的东西。它应该插入这些值,但我无法通过php插入 ID 。我无法获得正确的语法,请帮忙。
$insertQuery = "insert into appointment (appointmentID, doctorid, appointmentDate, symptoms, patientid, time)
values($id,(select doctorid from doctors where doctorName like '$docName'),$date,$symptoms,
(select patientid from patient where patientFName like '$nameOfUser'),$time)";
我收到一个无效的查询错误,但是当我对这些变量($docName, $id, $nameOfUser)
进行vardump时,结果却是正确的格式。我已经尝试在MySQL表中手动输入,并且已成功插入。
答案 0 :(得分:1)
首先,您通过使用(select patientid from patient where patientFName like '$nameOfUser')
选择已使用的ID来犯错误。我建议patientid是主键和整数数据类型。
创建表格时。使用此语法使其自动递增:
CREATE TABLE example (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM;
当您插入表格时,您不必插入ID。数据库引擎将自动计算最后一个ID。
INSERT INTO example(name)values('example');
但是!如果您已经在没有auto_increment
命令的情况下创建了此表,并且您已经使用了这个表太远了,请使用此解决方案:
mysql_connect('your host','database user','password');
mysql_select_db('your database name');
$query=mysql_query('SELECT MAX(patientid) FROM yourtable;');
$read_id = mysql_fetch_row($query));
$next_id = $read_id[0] + 1;
$query = mysql_query('INSERT INTO yourtable(patientid)values('.$next_id.');');
有关详细信息,请了解here
答案 1 :(得分:1)
$insertQuery = "INSERT INTO appointment
( appointmentID
, doctorid
, appointmentDate
, symptoms
, patientid
, time
)
SELECT '" . $id . "'
, n.doctorid
, '" . $date . "'
, '". $symptoms ."'
, p.patientid
FROM ( SELECT e.doctorid
FROM doctors e
WHERE e.doctorName LIKE '" . $docName . "'
LIMIT 1
) d
CROSS
JOIN ( SELECT q.patientid
FROM patient q
WHERE q.patientName LIKE '" . $nameOfUser ."'
LIMIT 1
) p ";
此语句受SQL注入。为了减轻这种影响,您需要逃避"不安全" SQL文本中包含的值,或使用带有绑定占位符的预准备语句。
假设您正在使用mysqli接口的过程样式函数,并且该连接名为$con
$insertQuery = "INSERT INTO appointment
( appointmentID
, doctorid
, appointmentDate
, symptoms
, patientid
, time
)
SELECT '" . mysqli_real_escape_string($con, $id) . "'
, n.doctorid
, '" . mysqli_real_escape_string($con, $date) . "'
, '" . mysqli_real_escape_string($con, $symptoms) ."'
, p.patientid
FROM ( SELECT e.doctorid
FROM doctors e
WHERE e.doctorName LIKE '" . mysqli_real_escape_string($con, $docName) . "'
LIMIT 1
) d
CROSS
JOIN ( SELECT q.patientid
FROM patient q
WHERE q.patientName LIKE '" . mysqli_real_escape_string($con, $nameOfUser) ."'
LIMIT 1
) p ";
准备好的语句将用绑定占位符替换文字:
$insertQuery = "INSERT INTO appointment
( appointmentID
, doctorid
, appointmentDate
, symptoms
, patientid
, time
)
SELECT ?
, n.doctorid
, ?
, ?
, p.patientid
FROM ( SELECT e.doctorid
FROM doctors e
WHERE e.doctorName LIKE ?
LIMIT 1
) d
CROSS
JOIN ( SELECT q.patientid
FROM patient q
WHERE q.patientName LIKE ?
LIMIT 1
) p ";