如何计算字符串中的单个值并在 PHP 中将其递增 1


how to count a single value in a string and increment it 1 by one in php

我正在创建一个简单而动态的函数,用于将值插入MySQL数据库表。 因此,参数绑定出现了问题。 所以我需要知道如何计算该查询字符串中有多少"?"标记以及如何逐个递增它。 因此,如果有人对此有很好的答案,请告诉我。这是我为此编写的函数

function insertValues($table,$fields,$values){
    global $pdo;
    $field_include = '';
    $value_include = '';
    if(is_array($fields))
    {
        foreach ($fields as $key => $value) 
        {
            $field_include .= ($key == 0) ? $value : ','.$value;
        }
    }
    if(is_array($values))
    {
        foreach ($fields as $key => $value) 
        {
            $value_include .= ($key == 0) ? "?" : ','.'?';
        }
    }
    $sql = $pdo->prepare('INSERT INTO '.$table.'('.$field_include.') VALUES ('.$value_include.')');
    $sql->execute(array($value_include));

谢谢

您之前$value_include为带有问号的字符串。我认为您需要在此行中使用$values array($value_include)

$sql->execute(array($value_include));

更新:

function insertValues($table,$fields,$values){
    global $pdo;
    $field_include = '';
    $value_include = '';
    if(is_array($fields))
    {
        foreach ($fields as $key => $value) 
        {
            $field_include .= ($key == 0) ? $value : ','.$value;
        }
    }
    if(is_array($values))
    {
        //Replaced $fields with $values 
        foreach ($values as $key => $value) 
        {
            $value_include .= ($key == 0) ? "?" : ','.'?';
        }
    }
    $sql = $pdo->prepare('INSERT INTO '.$table.'('.$field_include.') VALUES ('.$value_include.')');
    $sql->execute($values);