我已多次做过这种类型的SELECT,但这次我无法让它工作。有什么想法吗?
$Name = "Dick";
$conn = mysqli_connect($server, $dbname, $dbpw, $dbuser);
$sql = "SELECT id FROM table WHERE $Name = table.first_name";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$customer_id = $row['id'];
Database::disconnect();
echo "customer id = " . $customer_id;
答案 0 :(得分:2)
如果你确实有一个名为table
的表格,那么在名称周围使用反向标记会更合适,因为单词TABLE
是reserved word in MySQL。如果变量包含字符串,则还应在变量周围使用单引号:
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
如果查询仍然不适合您,可能还有其他原因:
mysqli_connect($server, $dbuser, $dbpw, $dbname)
。 fetch_array()
而不是fetch_assoc()
。mysqli_connect()
而不是mysqli()
时,使用面向对象样式的$result->
混合使用PROCEDURAL STYLE和面向对象样式。你应该决定一种风格并坚持下去。 这将是您查询的程序样式:
$Name = "Dick";
$conn = mysqli_connect($server, $dbuser, $dbpw, $dbname); // NOTE THE CHANGED ORDER OF CONNECTION PARAMETERS!
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$customer_id = $row['id']; // YOUR CUSTOMER ID
mysqli_free_result($result); // FREE RESULT SET
mysqli_close($conn); // CLOSE CONNECTION
这将是面向对象的风格:
$Name = "Dick";
$conn = new mysqli($server, $dbuser, $dbpw, $dbname);
$sql = "SELECT `id` FROM `table` WHERE `first_name` = '$Name'";
$result = $conn->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
$customer_id = $row['id']; // YOUR CUSTOMER ID
$result->free(); // FREE RESULT SET
$conn->close(); // CLOSE CONNECTION
我建议将您的表命名为table
,因为它是一个保留字,可以让您解决问题。字段名称也是如此。更多阅读:https://dev.mysql.com/doc/refman/5.5/en/keywords.html
有关mysqli_fetch_array()
的更多信息以及程序样式和面向对象样式使用的差异:http://php.net/manual/en/mysqli-result.fetch-array.php
答案 1 :(得分:1)
$sql = "SELECT id FROM table WHERE '$Name' = table.first_name";
答案 2 :(得分:0)
你只需要像这样连接变量:
$sql = "SELECT id FROM table WHERE " . $Name . " = table.first_name";