【问题标题】:Results UNDEFINED in SQL query and phpSQL查询和php中的结果未定义
【发布时间】:2015-08-14 09:20:11
【问题描述】:

我是 php、SQL 和仍在学习的新手,我正在尝试获取我的列的最后 4 个字符串值,其中值是电话号码:(7258787) 我正在尝试显示最后 4 个字符串,即使搜索查询是完整的 7 个字符串(8787),基于我已阅读的内容 SUBSTRING(column_name, -4) 将导致右侧的最后 4 个字符串。 我的代码返回未定义,您能告诉我吗?

    if (isset($_GET['telephone'])) {
    $data = "%".$_GET['telephone']."%";
    $sql = 'SELECT telephone, SUBSTRING(telephone,-4)FROM employee';

使用这个:

   $sql = 'SELECT * FROM employee WHERE telephone like ?';

将产生正确的值 7258787,但它会产生我在搜索框中键入的整个字符串(电话号码)

提前谢谢你

这是整个代码:

这不是答案,而是整个剧本,(感谢 Israel Barragan) 在我的数据库中,我将员工作为表,列是“ID”、“NAME”、“TELEPHONE”和“EMAIL”

<?php

header('Content-Type: application/json');
require_once 'Connectiondb.php';
$conn = dbConnect();
$OK = true; // We use this to verify the status of the update.

if (isset($_GET['telephone'])) {
    // Create the query
    $data = "%".$_GET['telephone']."%";
    $sql = 'SELECT * FROM employee WHERE telephone like ?';
    // we have to tell the PDO that we are going to send values to the query
    $stmt = $conn->prepare($sql);
    // Now we execute the query passing an array toe execute();
    $results = $stmt->execute(array($data));
    // Extract the values from $result
    $rows = $stmt->fetchAll();
    $error = $stmt->errorInfo();
    //echo $error[2];
}
// If there are no records.
if(empty($rows)) {
    echo json_encode( array('error'=>'There were not records','0'=> 'There            were not records'));
}
else {
    echo json_encode($rows);
}
?>

对不起,我是stackoverflow的新手,

【问题讨论】:

  • 你能再贴一些代码吗?你如何选择第二个查询?在转到下一页之前,您是否尝试过打印结果?
  • 这是什么数据库?尝试在 `SUBSTRING(telephone,-4)FROM` 中放置一个列别名和一个空格,使其看起来像 `SUBSTRING(telephone,-4) as phoneLastFour FROM`
  • 好吧抱歉让我把整个代码放上来,谢谢
  • @Leiagh 编辑你的原帖添加代码,请不要放在cmets中

标签: php sql substring


【解决方案1】:

您可以在查询中绑定结果,然后从中获取最后 4 位进行显示。

例如,您可以这样做

(不是你没有绑定你的参数。你需要做这样的事情)

$stmt->bind_param("s", $data);

然后像这样执行它:

$stmt->execute();

在您的查询中,而不是使用select *,命名特定键,然后您可以像这样绑定结果(假设您只需要电话号码:

$stmt->bind_result($telephone);

然后得到这样的结果:

$stmt->fetch();

那么您可以像这样从$telephone 中获取一个子字符串(在php 中是substr()

echo substr($telephone,-4);

(哦,是的,别忘了用

关闭你的对象
$stmt->close();

完成后)

编辑:
这是您的查询放在一起以获取子字符串

$data = "%".$_GET['telephone']."%";
$stmt = $conn->prepare("SELECT telephone FROM employee WHERE telephone like ?");
$stmt->bind_param("s", $data);
$stmt->execute();
$stmt->bind_result($telephone);
$stmt->fetch();
echo substr($telephone,-4);
$stmt->close();

【讨论】:

  • 我遇到了问题; :((
  • @Leiagh 不确定您仍然遇到什么问题,但我编辑了我的答案以将它们放在一起。上面的代码应该适合你
猜你喜欢
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2012-12-30
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多