php - 使用在单独函数中创建的字符串插入到表中

标签 php mysql

我尝试使用在单独函数中创建的字符串进行插入,但它似乎不起作用。

我知道我应该使用 switch 语句或其他语句来实现此目的,但目前它纯粹用于测试。

<?php
function newItem($link){
    $itemname = mysqli_real_escape_string($link, $_POST['itemname']);
    if (strpos($itemname,'<') || strpos($itemname,'>') || strpos($itemname,'?') || strpos($itemname,'/') || strpos($itemname,'=')) 
    {
        echo "<script type='text/javascript'>alert('yeah....no');</script>";
    } else { 
        $sql = "SELECT * FROM items WHERE itemname = '$itemname'";
        $result = mysqli_query($link,$sql);
        if(mysqli_num_rows($result) !== 1){
            $sql = "INSERT INTO items(itemname,itemtype,attack,defence,energy)VALUES('$itemname'".RandomStats($link).")";
            mysqli_query($link,$sql);
            header("location: index.php");
        }else{
            echo "<script type='text/javascript'>alert('Item name already exists');</script>";
        }
    } 
}
function RandomStats($link){
    $rand = rand ( 1 , 100 );
    $itemtype = rand (1,3);
    $itemtypeString;

    if($itemtype = 1){
        $itemtypeString = 'Armour';
    }
    if($itemtype = 2){
        $itemtypeString = 'Sword';
    }
    if($itemtype = 3){
        $itemtypeString = 'Shield';
    }

    if($rand <= 50){
        //common
        $attack = rand (1 , 50);
        $defence = rand (1 , 50);
        $energy = rand (1 , 50);
        $ItemStats = "','".$itemtypeString."','".$attack."','".$defence."','".$energy."'";
    }
    if ($rand >50 and $rand <= 80){
        //rare
        $attack = rand (1 , 100);
        $defence = rand (1 , 100);
        $energy = rand (1 , 100);
        $ItemStats = "','".$itemtypeString."','".$attack."','".$defence."','".$energy."'";
    }
    if ($rand >80 and $rand <= 98){
        //exotic
        $attack = rand (1 , 150);
        $defence = rand (1 , 150);
        $energy = rand (1 , 150);
        $ItemStats = "','".$itemtypeString."','".$attack."','".$defence."','".$energy."'";
    }
    if ($rand >98 and $rand <= 100){
        //ledgendary
        $attack = rand (1 , 200);
        $defence = rand (1 , 200);
        $energy = rand (1 , 200);
        $ItemStats = "','".$itemtypeString."','".$attack."','".$defence."','".$energy."'";
    }

    return $ItemStats;
}
?>

只是我创建字符串的方式使语句不正确还是有其他原因?

最佳答案

我在开始时有一个额外的 ' ,在 u_mulder 帮助我进行调试后就不需要了

关于php - 使用在单独函数中创建的字符串插入到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39558750/

相关文章:

PHP 数组替换

php - Facebook 应用程序选项卡 -> 使用 PHP 进行外部链接

php - 如何将两个值API传递给android?

mysql - 在Windows 7中的mysql 5.7中创建多个实例

php - 在 opencart 中,当表中存在记录时,SELECT 查询给出空结果

php - 带时间戳的数据库,显示不同的月份

php - 解析错误 : syntax error, 文件意外结束,需要 elseif (T_ELSEIF) or else (T_ELSE) or endif (T_ENDIF)

php - 使用 PHP 将复选框值插入 MySQL 数据库

php - 使用html和php将图像上传到mysql

php - MySql 查询以检索 xml 的元素属性的值