简体   繁体   English

PHP查询从多个表中插入数据

[英]PHP Query inserting data from multiple tables

I have table A(predictions) consisting of columns from table B(fixtures) and table C(user registration table). 我有表A(预测),该表由表B(固定装置)和表C(用户注册表)的列组成。 Each time a new user registers I want to add their username to table A along with a data from all data from table B. 每次有新用户注册时,我都希望将其用户名以及表B中所有数据中的数据添加到表A中。

When I register a new user it only inserts the users data into table A(predictions) and the first row from table B(predictions). 当我注册一个新用户时,它只会将用户数据插入表A(预测)和表B(预测)的第一行。

What i want to achieve is; 我想实现的是 when a new user registers their username name will be added into the username column along with along the fixtures from the season, therefore the username is inserted in each row for each fixture: 当新用户注册时,其用户名将与季节中的灯具一起添加到用户名列中,因此,用户名将插入每个灯具的每一行中:

Pred_ID | Pred_ID | Fix_ID | Fix_ID | Home_Team | 主页_团队| Home_Score | 主页_得分| Away_Score | Away_Score | Away_Team | 客队| username 用户名

1 -----------1 -------Man U------------------- 7-------------0-----------------Arsenal------B.Rubble 1 ----------- 1 ------- Man U ------------------- 7 -------- ----- 0 -----------------阿森纳------ B.Rubble

2 -----------1 -------Man U------------------- 5-------------0----------------Arsenal-------B.Rubble 2 ----------- 1 ------- Man U ------------------- 5 -------- ----- 0 ----------------阿森纳------- B.Rubble

3 -----------2 -------Chelsea------------------0-------------1----------------Leister-------New.user 3 ----------- 2 -------切尔西------------------ 0 ---------- --- 1 ----------------莱丹------- New.user

4 -----------2 -------Chelsea------------------ 0------------3----------------Leister--------New.user 4 ----------- 2 -------切尔西------------------ 0 ---------- --3 ----------------莱斯特-------- New.user

Using The insert function 使用插入功能

public function insert($table, $fields = array()) {

    $keys   = array_keys($fields);
    $values = '';
    $x      = 1;

    foreach ($fields as $field) {
        $values .= '?';
        if ($x < count($fields)) {

            $values .= ', ';
        } //are we at end of defined fields

        $x++;
    }


    $sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";

    if (!$this->query($sql, $fields)->error()) {
        return true;
    }


    return false;
}

Im using the following updatePredTable() function 我正在使用以下updatePredTable()函数

public function updatePredTable($fields=array()){
    if(!$this->_db->insert('predict', $fields)) {
        throw new Exception('There was a problem creating an account');
    }
}

register.php register.php

<?php
require_once 'core/init.php';

include 'navbar.php';

$prediction = DB::getInstance()->query("SELECT * FROM fixtures");

if (!$prediction->count()) {
    echo 'No preds';
} else {  
    foreach ($prediction->results() as $row) {

        $row = get_object_vars($row);
        echo $row['Home_Team'], '<br>';

        if (Input::exists()) {
            if (Token::check(Input::get('token'))) {

                var_dump(Token::check(Input::get('token')));


                //echo 'I have been run'; 
                $validate   = new Validate();
                $validation = $validate->check($_POST, array(

                    'username' => array(

                        'required' => true,
                        'min' => 2,
                        'max' => 20,
                        'unique' => 'users'
                    ),
                    'password' => array(

                        'required' => true,
                        'min' => 6


                    ),
                    'password_again' => array(

                        'required' => true,
                        'matches' => 'password'
                    ),
                    'name' => array(

                        'required' => true,
                        'min' => 2,
                        'max' => 50
                    )

                ));

                if ($validation->passed()) {

                    //Session::flash('Success', 'You registered successfully!');
                    //header('Location: index.php');

                    $user = new User();
                    $salt = Hash::salt(32);

                    try {

                        $user->create(array(

                            'username' => Input::get('username'),
                            'password' => Hash::make(Input::get('password'), $salt),
                            'salt' => $salt,
                            'name' => Input::get('name'),
                            'joined' => date('Y-m-d H:i:s'),
                            'group' => 1   
                        ));

                        $user->updatePredTable(array(
                            'username' => Input::get('username'),
                            'fixture_ID' => $row['Fixture_ID'],
                            'date' => $row['Date'],
                            'home_Team' => $row['Home_Team'],
                            'away_Team' => $row['Away_Team']
                        ));

                        Session::flash('home', 'You have been registered you can now log in!');
                        //like:
                        //header('Location: index.php');

                        Redirect::to('index.php');  
                    }
                    catch (Exception $e) {
                        die($e->getMessage());
                    }
                    //echo 'Passed';
                } else {
                    foreach ($validation->errors() as $error) {
                        echo $error, '<br>';
                        //print_r($validation->errors());
                    }
                }
            }
        }
    }  
}


?>

I think you need to look at where you loop over the predictions result set. 我认为您需要查看循环遍历预测结果集的位置。 It looks like on the first iteration you are redirecting to index.php hence only one row is added try looping over the resultset as below 看起来像在第一次迭代中,您将重定向到index.php,因此仅添加了一行,尝试遍历结果集,如下所示

 <?php
require_once 'core/init.php';

include 'navbar.php';

$prediction = DB::getInstance()->query("SELECT * FROM fixtures");

if (!$prediction->count()) {
    echo 'No preds';
} else {  


        if (Input::exists()) {
            if (Token::check(Input::get('token'))) {

                var_dump(Token::check(Input::get('token')));


                //echo 'I have been run'; 
                $validate   = new Validate();
                $validation = $validate->check($_POST, array(

                    'username' => array(

                        'required' => true,
                        'min' => 2,
                        'max' => 20,
                        'unique' => 'users'
                    ),
                    'password' => array(

                        'required' => true,
                        'min' => 6


                    ),
                    'password_again' => array(

                        'required' => true,
                        'matches' => 'password'
                    ),
                    'name' => array(

                        'required' => true,
                        'min' => 2,
                        'max' => 50
                    )

                ));

                if ($validation->passed()) {

                    //Session::flash('Success', 'You registered successfully!');
                    //header('Location: index.php');

                    $user = new User();
                    $salt = Hash::salt(32);

                    try {

                        $user->create(array(

                            'username' => Input::get('username'),
                            'password' => Hash::make(Input::get('password'), $salt),
                            'salt' => $salt,
                            'name' => Input::get('name'),
                            'joined' => date('Y-m-d H:i:s'),
                            'group' => 1   
                        ));

foreach ($prediction->results() as $row) {

        $row = get_object_vars($row);
        echo $row['Home_Team'], '<br>';

                        $user->updatePredTable(array(
                            'username' => Input::get('username'),
                            'fixture_ID' => $row['Fixture_ID'],
                            'date' => $row['Date'],
                            'home_Team' => $row['Home_Team'],
                            'away_Team' => $row['Away_Team']
                        ));
}
                        Session::flash('home', 'You have been registered you can now log in!');
                        //like:
                        //header('Location: index.php');

                        Redirect::to('index.php');  
                    }
                    catch (Exception $e) {
                        die($e->getMessage());
                    }
                    //echo 'Passed';
                } else {
                    foreach ($validation->errors() as $error) {
                        echo $error, '<br>';
                        //print_r($validation->errors());
                    }
                }

        }
    }  
}

I haven't tested this but hopefully it will point you in the right direction 我尚未对此进行测试,但希望它将为您指明正确的方向

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM