此代码并不漂亮,但我想从表格studentcourseplan
打印出上次生成的自动增量ID
<?php
session_start();
if (!isset($_SESSION['session_username']) ) { header ("Location: login.php");exit;} //If user in not signed in, redirect to login page
include("dbconfig.php");
if (isset($_POST['course_id'])) {
$course_id = $_POST['course_id'];
$student_id = $_POST['student_id'];
$start_date = $_POST['start_date'];
$end_date = $_POST['end_date'];
$studentcourseplan_update = mysql_query("
INSERT INTO studentcourseplan (student_id,cpl_startdate, cpl_enddate, cpl_coursename, cpl_pricevalue)
SELECT '$student_id','$start_date', '$end_date', course_name, price_value
FROM courses c
INNER JOIN pricegroups p ON p.price_id = c.course_price_id
WHERE c.course_id = '$course_id'");
$result = mysql_query("SELECT LAST_INSERT_ID() FROM studentcourseplan");
$row = mysql_fetch_assoc($result);
$cpl_id = $row['cpl_id'];
$studentcourseplanelements_update = mysql_query("
INSERT INTO studentcourseplanelements (scpe_cpl_id, scpe_name, scpe_days)
SELECT LAST_INSERT_ID(), cp.plan_name, cp.plan_time FROM courses c
INNER JOIN course_to_plan cpl ON cpl.course_id = c.course_id
INNER JOIN courseplans cp ON cp.plan_id = cpl.plan_id
WHERE cpl.course_id = '$course_id'");
$courseinfo = mysql_query("SELECT * FROM studentcourseplan WHERE cpl_id = '$cpl_id'") or die(mysql_error());
if ($studentcourseplan_update === true) {
while ($result = mysql_fetch_assoc($courseinfo)) {
echo $result['cpl_id'];
}
} else if ($studentcourseplan_update === false){
echo "Kunde inte uppdatera.";
}
}
?>
第24行发出的声音是:
$cpl_id = $row['cpl_id'];
我在第24行的\ Path \ To \ Page.php中获得未定义的索引:cpl_id
答案 0 :(得分:3)
因为您在第一个选择查询中仅选择了LAST_INSERT_ID()
:
$result = mysql_query("SELECT LAST_INSERT_ID() FROM studentcourseplan");
$row = mysql_fetch_assoc($result);
// Doesn't exist, only $row['LAST_INSERT_ID()']
$cpl_id = $row['cpl_id'];
// Probably you meant
$cpl_id = $row['LAST_INSERT_ID()'];
相反,您只需调用mysql_insert_id()
而不是执行查询来检索它。
$cpl_id = mysql_insert_id();
您的查询易受当前表单中的SQL注入攻击。请务必在用作查询输入的所有mysql_real_escape_string()
变量上调用$_POST
。
$course_id = mysql_real_escape_string($_POST['course_id']);
$student_id = mysql_real_escape_string($_POST['student_id']);
$start_date = mysql_real_escape_string($_POST['start_date']);
$end_date = mysql_real_escape_string($_POST['end_date']);
从长远来看,建议远离mysql_*()
函数,而是学习使用支持PDO或MySQLi等预处理语句的更现代的API。