$wpdb->insert() 保存了带有格式的数据。为什么?以及如何避免这种情况?



我正在使用wordpress 4.7,我有一些数据,想使用全局$wpdb将它们插入我的数据库中,但问题是数据被保存为保存在例如wp_post_meta表中,例如s:4:"asdf";s:2:"on";。 我之前以完全相同的方式使用它,并且没有这个问题。是有什么变化还是我做错了什么?

这是我的完整代码:

$table_name=$wpdb->prefix.'products';
$wpdb->insert($table_name,array('name'=>$product_name,'price'=>$product_price,'size'=>$product_size,'status'=>$instore,'shortcode'=>'asdf'),array( '%s', '%d','%s','%s','%s' ));

这是我读取数据库时的返回值,所以你可以看到它是如何存储在数据库中

array (size=1)
0 => 
object(stdClass)[700]
public 'id' => string '1' (length=1)
public 'name' => string 's:4:"asdf";' (length=11)
public 'price' => string 's:3:"234";' (length=10)
public 'size' => string 's:2:"on";' (length=9)
public 'status' => string 'N;' (length=2)
public 'shortcode' => string 'asdf' (length=4)

如您所见,我没有得到实际值,而是带有s:前缀的值。我希望这些值存储为普通的并且没有这个前缀的东西。

这是我$_POSTvar_dump()输出

array (size=4)
'new-product' => string 'yes' (length=3)
'product-name' => string 'sdf' (length=3)
'product-price' => string '1' (length=1)
'product-size' => string 'on' (length=2)
$product_name=$_POST['product-name'];
$product_price=$_POST['product-price'];
if(isset($_POST['product-size'])){
$product_size=$_POST['product-size'];
}else{
$product_size='N';
}
if (isset($_POST['instore'])){
$instore=$_POST['instore'];
}else{
$instore='N';
}

在我看来,您在某处的代码中使用了serialize,这使得返回具有此类变量类型的值。删除它应该可以解决您的问题。因此,如果您有:

$product_name = serialize($_POST['product-name']);

将其更改为:

$product_name = $_POST['product-name'];

或者,如果您像这样在整个 _POST 美元上使用它:

serialize($_POST)

删除serialize()它,它应该可以工作。

或者不必删除serialize只需在插入数据库之前使用unserialize($_POST['product-name'])

相关内容

最新更新