PHP $ _POST存储为单词'Array'

时间:2016-01-20 12:50:01

标签: php arrays post

我遇到了从表单存储输入数据的问题。存储在数据库中的所有内容都是“数组”一词。似乎我必须对发布数据做些什么才能正确存储。无法让它正常工作。任何帮助表示赞赏。以下是处理输入表单的代码。

<?php

session_start();

/* variables */
$a1 = $_POST['value1'];
$a2 = $_POST['value2'];
$a3 = $_SESSION['user_id'];

/* connect */
$mysqli = new mysqli("xxxx","xxxx","xxxx","xxxx");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if (!($stmt = $mysqli->prepare("UPDATE table1 SET column1 =? WHERE user_id=? "))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!($stmt2 = $mysqli->prepare("UPDATE table1 SET column2 =? WHERE user_id=? "))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

/* bind parameters for markers */
if (!$stmt->bind_param("ss", $a1, $a3)) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt2->bind_param("ss", $a2, $a3)) {
    echo "Binding parameters failed: (" . $stmt2->errno . ") " . $stmt2->error;
}

/* loop and execute */
foreach($a1 as $key => $value){
            $key++;     
        if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
        }
    }

foreach($a2 as $key => $value){
            $key++;     
        if (!$stmt2->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
        }
    }

$stmt->close();
$stmt2->close();

想知道变量是否包含数据:

/* show data from the post*/
echo "<pre>";
var_dump($a1);
echo "</pre><br>";
echo "<pre>";
var_dump($a2);
echo "</pre><br>";

原来确实如此,它与输入相匹配。输出:

 array(30) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "1"
  [2]=>
  string(1) "1"
  etc..
 }

 array(30) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "1"
  [2]=>
  string(1) "3"
  etc...
 }

它只是在应该有输入值的地方存储“数组”这个词。有人能指出我正确的方向吗?我被困住了,可以真正使用一些帮助。

编辑:这是一个关于足球比赛的简单网站。爱好项目:D Value1是主队得分的目标,客队的得分值是2。 $ _POST是两个球队为特定用户的几场比赛得分的输入。

Edit2:从发送表单和使用的表格中添加了代码:

//....connection, select query, etc....

$result=mysqli_query($mysqli,$sql);

while($row = $result->fetch_array())
{
$rows[] = $row;
}
?>

//....form and tabel stuff....
    <form action="send1.php" method="post"> 
        <div class="table-responsive">  
            <table class="table">
                <thead>
                    <tr>
                        <th class="col-md-2">Date</th>
                        <th class="col-sm-1">Time</th>
                        <th class="col-md-2">Home - Away</th>
                        <th class="col-sm-1">Home</th>
                        <th class="col-sm-1">Away</th>
                    </tr>
                </thead>
            <tbody>                                                                     
<?php

foreach($rows as $row){

?>                          
                    <tr>
                        <td class="col-md-2"><?php echo $row['date']; ?></td>
                        <td class="col-sm-1"><?php echo $row['time']; ?></td>
                        <td class="col-md-2">
                            <span class="hidden-xs"><?php echo $row['Team_Home']; ?> - <?php echo $row['Team_Away']; ?></span>
                            <span class="visible-xs-block">test1 - test2</span>
                        </td>                                           
                        <td class="col-sm-1"><input type="text" name="score1[]" style="height:20px; width:32px"></td>   
                        <td class="col-sm-1"><input type="text" name="score2[]" style="height:20px; width:32px"></td>                                       
                    </tr>                                   
<?php  

}  

$result->close();

?>  

//....more table stuff with submit button...

<?php
mysqli_close();
?>

输出就像10+行,输入主队和客队的得分。

数据来源的表格如下:

  • 匹配
    • Match_id
    • 日期
    • 时间
    • 体育场
    • Team_home
    • Team_away
    • Score_home
    • Score_away

目前这些预测看起来像这样:

  • 预测
    • Prediction_id
    • Match_id
    • User_id
    • Score_predict_home
    • Score_predict_away

所以我想要1个表中的所有匹配数据和另一个表中的预测。

Edit3:这就是我现在所做的。没有更多的PHP错误:D数据在数组中但不会在db中结束:(

$acMatchPredictions = !empty($_POST['match_prediction']) &&       
is_array($_POST['match_prediction']) ? $_POST['match_prediction'] : array();

foreach($acMatchPredictions as $wedstrijd_id => $aPredictedScores) {
    $score_predict_home = (int) $aPredictedScores['score_predict_home'];
    $score_predict_away = (int) $aPredictedScores['score_predict_away'];
    $user_id = $_SESSION['user_id'];

$query = ('update predictions set score_predict_home=?, score_predict_away=? where match_id=? and user_id=?');

$stmt = $mysqli->prepare($query); 

$stmt->bind_param('iiii', $match_id, $user_id, $score_predict_home, $score_predict_away);

$stmt->execute();

}

$stmt->close();

echo "<pre>";
var_dump($acMatchPredictions);
echo "</pre><br>";

var_dump的输出:

array(72) {
  [0]=>
  array(1) {
    ["score_predict_home"]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    ["score_predict_away"]=>
    string(1) "3"
  }
  [2]=>
  array(1) {
    ["score_predict_home"]=>
    string(1) "1"
  }
  [3]=>
  array(1) {
    ["score_predict_away"]=>
    string(1) "3"
  }

2 个答案:

答案 0 :(得分:0)

如果要保存完整数组,请使用:

recording $saveArray = serialize ($myArray);

获取使用数组:

$myArray = unserialize($arrayInMysql);

如果保存循环内的内容,请将过去的参数放在foreach中:

$stmt->bind_param("ss", $ value, $ a3) ...

答案 1 :(得分:0)

如果您在数据库中持有序列化的应用程序代码,那么您可能会反过来考虑系统。数据库应该为您的需求建模,应用程序应该简单地与它进行交互。

因此,对于足球设备,您可能需要在数据库中使用多个表,例如:

<强>队

  • ID
  • 名称
  • stadium_id

<强>体育场

  • ID
  • 名称

<强>匹配

  • ID
  • 日期
  • stadium_id
  • home_team_id
  • HOME_TEAM_SCORE
  • away_team_id
  • AWAY_TEAM_SCORE

<强>预测

  • ID
  • match_id
  • USER_ID
  • HOME_TEAM_SCORE
  • AWAY_TEAM_SCORE

据推测,这些是网站用户预测的匹配结果,因此是 user_id 列。

如果我正确理解了这个问题,你就会生成一个匹配列表,并允许人们为他们设置分数预测。

您的HTML表单现在看起来像:

&#13;
&#13;
<form action="send1.php" method="post" style="font-family: sans-serif;">                 
<?php foreach($matches as $match): ?>

	<div class="fixture">
		<h2>Fixture</h2>
		<div class="fx date"><span>Date:</span> <?= $match['date']; ?></div>
		<div class="fx stadium"><span>Stadium:</span> <?= $match['stadium_name']; ?></div>

		<div class="fx home_team">
			<div class="title">Home Team : <?= $match['home_team_name']; ?></div>
			<div class="score"><label>Predicted score: 
				<input type="text" name="match_prediction[<?= $match['id']; ?>][home_score]" />
			</label></div>
		</div>

		<div class="fx away_team">
			<div class="title">Away Team : <?= $match['away_team_name']; ?></div>
			<div class="score"><label>Predicted score:
				<input type="text" name="match_prediction['<?= $match['id']; ?>][away_score]" />
			</label></div>
		</div>
	</div>

<?php endforeach; ?>
</form>
&#13;
&#13;
&#13;

这应该会为您提供一个用户可以插入其分数预测的灯具列表。

数据作为数组传递给PHP,使用匹配id作为键。

因此,对于第1,2和34场比赛,预测列表可能如下所示:

$_POST = array(
    match_prediction[1]['home_score'] = 1,
    match_prediction[1]['away_score'] = 2,
    match_prediction[12]['home_score'] = 3,
    match_prediction[12]['away_score'] = 1,
    match_prediction[34]['home_score'] = 2,
    match_prediction[34]['away_score'] = 2
);

然后获取该数据以将其插入数据库,您只需循环遍历$ _POST数组:

$acMatchPredictions = !empty($_POST['match_prediction']) && is_array($_POST['match_prediction']) ? 
    $_POST['match_prediction'] :
    array();

foreach($acMatchPredictions as $iMatchId => $aPredictedScores) {
    $iHomeScore = (int) $aPredictedScores['home_score'];
    $iAwayScore = (int) $aPredictedScores['away_score'];
    $iUserId = {wherever your user id comes from, session?};

    //query to insert this prediction
    $sqy = "INSERT INTO prediction (match_id, user_id, home_team_score, away_team_score) "
        . "VALUES(?, ?, ?, ?)";

    //prepare the statement
    $stmt = $mysqli->prepare($qry);

    //bind parameters
    if(!$stmt->bind_param('iiii', $iMatchId, $iUserId, $iHomeScore, $iAwayScore)) {
        //trap the error ...
    }

    //execure and so on ...
    // ...

}

这遵循数据库规范化的基本规则: https://en.wikipedia.org/wiki/Database_normalization

如果您开始将序列化的应用程序代码放入数据库中,那么在更新应用程序时,数据库本身可能会完全过时。如果您将数据与流程完全分开(MVC背后的原则之一),您将不会遇到此问题。