如何将SQL语言与PHP语言混合使用

时间:2016-04-12 18:41:08

标签: php sql mysqli

我写了这段代码:

<?php
$con = mysqli_connect('localhost', 'root', '');
if(!$con)
{
    die("not ok");
}

mysqli_select_db($con,"uoh");  

$q = " SELECT * FROM student WHERE id = 201102887" ;
$result = mysqli_query($con , $q ) ;
if($row = mysqli_fetch_array($result))
{
   echo "<h3> compliance for for " . $row["name"];
   echo " and the major is ".$row["major"];
   echo "</h3>";
}

$major=$row["major"];

$con = mysqli_connect('localhost', 'root', '');
if(!$con)
{
    die("not ok");
}

mysqli_select_db($con,"uoh");  
$q = "SELECT * FROM courses LEFT JOIN equal ON equal.course_number= 
courses.course_number LEFT JOIN degree_plan ON degree_plan.course_number=
 courses.course_number LEFT JOIN student_record ON courses.course_number= 
 student_record.course_number AND student_record.id=201102887 AND degree_plan.major=".$major;
?>

代码工作正常,但没有给我一个结果。

我认为问题出在degree_plan.major=".$major; 因为查询没有给我一个结果。

你能解决吗?

2 个答案:

答案 0 :(得分:0)

您没有执行仅定义为字符串的第二个查询。您应该在第二次查询之后放置类似于第一次查询的内容

$result2 = mysqli_query($con , $q ) ;
if($row2 = mysqli_fetch_array($result2)) {

由于主要值看起来像一个字符串,您可能需要用引号括起来,否则您的查询将失败

AND degree_plan.major='".$major."'";

答案 1 :(得分:0)

您应该使用引号格式化查询

    mysqli_select_db($con,"uoh");  
    $q = "SELECT * FROM courses LEFT JOIN equal ON equal.course_number= 
     courses.course_number LEFT JOIN degree_plan ON degree_plan.course_number=
     courses.course_number LEFT JOIN student_record ON courses.course_number= 
     student_record.course_number 
      AND student_record.id=201102887 AND degree_plan.major='".$major ."'";