为什么我的json数据没有被插入mySQL数据库?

时间:2017-04-09 06:47:02

标签: php mysql json database webhooks

我创建了一个PHP处理程序,用于从POST请求接收JSON有效负载,然后将其插入到phpMyAdmin中的数据库中。我不确定为什么这不起作用。

JSON:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".DetailActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/iv_movie_backdrop"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:contentDescription="@string/str_movie_backdrop_image"
                android:scaleType="fitXY" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>


    <android.support.v4.widget.NestedScrollView xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="8dp"

        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v7.widget.CardView
                android:id="@+id/cv_poster_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:elevation="@dimen/card_elevation"
                app:cardCornerRadius="8dp"
                app:cardUseCompatPadding="true">

                <ImageView
                    android:id="@+id/iv_movie_poster"
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:contentDescription="@string/str_movie_poster"
                    android:padding="@dimen/poster_padding"
                    android:scaleType="fitXY"
                    android:src="@drawable/not_found" />
            </android.support.v7.widget.CardView>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toEndOf="@id/cv_poster_image"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/tv_movie_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="64dp"
                    android:layout_marginStart="8dp"
                    android:padding="@dimen/poster_padding"
                    android:textAppearance="?android:textAppearanceMedium"
                    android:textColor="@android:color/black"
                    android:textStyle="bold"
                    tools:text="Spider Man and Iron Man" />

                <TextView
                    android:id="@+id/tv_release_date"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:drawablePadding="@dimen/poster_padding"
                    android:drawableStart="@drawable/ic_date_range_black_24dp"
                    android:gravity="start"
                    android:padding="@dimen/poster_padding"
                    android:textAppearance="?android:textAppearanceSmall"
                    android:textColor="@android:color/black"
                    tools:text="March, 2017" />

                <TextView
                    android:id="@+id/tv_rating"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:drawablePadding="@dimen/poster_padding"
                    android:drawableStart="@drawable/ic_star_black_24dp"
                    android:gravity="start"
                    android:padding="@dimen/poster_padding"
                    android:textAppearance="?android:textAppearanceSmall"
                    android:textColor="@android:color/black"
                    tools:text="7.1" />

                <TextView
                    android:id="@+id/tv_genre"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:padding="@dimen/poster_padding"
                    android:textAppearance="?android:textAppearanceSmall"
                    android:textColor="@android:color/black"
                    android:textStyle="italic"
                    tools:text="Horror | Comedy | Drama" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/cv_poster_image"
                android:orientation="vertical">

                <android.support.design.widget.TabLayout
                    android:id="@+id/sliding_tabs"
                    style="@style/CategoryTab"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:tabGravity="fill" />

                <android.support.v4.view.ViewPager
                    android:id="@+id/viewPager"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

            </LinearLayout>
        </RelativeLayout>
    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"
        app:srcCompat="@drawable/ic_favorite_black_24dp" />

</android.support.design.widget.CoordinatorLayout>

我从在线教程获得的PHP代码。该教程是从2017年开始的,所以我假设一切都是最新的,但它仍然不起作用:

payload = {  
    "version":"1.0",
    "event":"video_recorded",
    "data":{
        "videoName":"vs1457013120534_862",
        "audioCodec":"NellyMoser ASAO",
        "videoCodec":"H.264",
        "type":"FLV",
        "orientation":"landscape",
        "id":"0",
        "dateTime":"2016-03-03 15:51:44",
        "timeZone":"Europe/Bucharest",
        "payload":"111.111.111.11",
        "httpReferer":"http://site_from_where_video_was_recorded.com"
    }
}

我将主键设置为int并使其自动增加。如果我理解正确,我不需要在该列中插入任何内容,因为它每次都会分配一个数字。或者,当我插入其他变量时,我是否还需要传递它?

3 个答案:

答案 0 :(得分:1)

这适用于数组部分,你得到正确答案。所以,你的代码还不错,但你应该检查所有错误(如Bhavin在评论中所述)。我确定你有一个错字 - &gt; $ vid_name = $ data_array ['data'] ['videName'];是 NOT ,例如$ vid_name = $ data_array ['data'] ['vide o 名称'];因此,error_reporting将非常有用,之后,检查查询是否有其他错误(预处理语句^^)

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

$payload = '{  
          "version":"1.0",
          "event":"video_recorded",
          "data": {
              "videoName":"vs1457013120534_862",
              "audioCodec":"NellyMoser ASAO",
              "videoCodec":"H.264",
              "type":"FLV",
              "orientation":"landscape",
              "id":"0",
              "dateTime":"2016-03-03 15:51:44",
              "timeZone":"Europe/Bucharest",
              "payload":"111.111.111.11",
                "httpReferer":"http://site_from_where_video_was_recorded.com"
          }
      }';

$data_array = json_decode($payload, true);

/* store in PHP variables */

$ip_address = $data_array['data']['payload'];
$vid_name = $data_array['data']['videoName'];
$date_time = $data_array['data']['dateTime'];
$time_zone = $data_array['data']['timeZone'];

echo"[ $ip_address / $vid_name / $date_time / $time_zone ]";

// EDIT : added query

include"config.inc.php";

// connect to DB
$mysqli = mysqli_connect("$host", "$user", "$mdp", "$db");

if (mysqli_connect_errno()) { echo "Error connecting : " . mysqli_connect_error($mysqli); }

$query = " INSERT INTO ip_and_videos (`IpAddress`, `VideoName`, `DateTime`, `Timezone`) VALUES (?,?,?,?) ";
$stmt = $mysqli->prepare($query);

print_r($stmt->error_list);

$stmt->bind_param("ssss", $ip_address, $vid_name, $date_time, $time_zone );

if (!$stmt->execute()) { echo $stmt->error; } else { echo"true"; }

?>

答案 1 :(得分:0)

不确定您是否有同样的问题,但这对我不起作用......

$vid_name = $data_array['data']['videName'];

我必须使用

$vid_name = $data_array->data->videoName;

不能将stdClass用作数组。

答案 2 :(得分:0)

应该这样更好

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

/* db variables */

$dbhost = 'localhost';
$dbname = 'name_db';
$dbuser = 'user_db';
$dbpass = 'pass_db';

/* grab the json */

$data = $_POST['payload'];

/* put json into php associative array */

$alldata = json_decode($data,true);
print_r($alldata);

/* connect to mysql db */

$con = mysql_connect($dbuser, $dbpass, $dbhost) or die('Could not connect: ' . mysql_error());

/* select the specific db */

mysql_select_db($dbname, $con);

/* insert the values into the db */
foreach($alldata as $data_array) {

$ip_address = $data_array['data']['payload'];
$vid_name = $data_array['data']['videoName'];
$date_time = $data_array['data']['dateTime'];
$time_zone = $data_array['data']['timeZone'];

$sql = "INSERT INTO ip_and_videos(IpAddress, VideoName, DateTime, Timezone) VALUES('".$ip_address."','".$vid_name."','".$date_time."','".$time_zone."')";
mysql_query($sql);
echo mysql_errno($con) . ": " . mysql_error($con) . "\n";
}

?>

希望这有帮助