简体   繁体   中英

Insert the content of an array in a database in php

I wrote this function that scrapes some content from a web page to my database. My issue is with my array variable $lang , everything works as I want when I test with print_r($lang) , but I am unable to insert the values in my DB because it looks like the array is empty when I used it in the second foreach .

Please guys, how can insert $lang in my DB properly? Here below is my code. Your help will be much appreciated. Thank you!

<?php

$html = file_get_html($url);
$links = array();
$lang = array();
foreach ($html->find('div.blockshadow h1') as $i => $title) {
    $textValue = $title->plaintext;
    if (strpos($textValue, 'VF') !== false) {
        $lang[] = 'VF';
    } elseif (strpos($textValue, 'VOSTFR') !== false) {
        $lang[] = 'VOSTFR';
    } elseif (strpos($textValue, 'VO') !== false) {
        $lang[] = 'VO';
    }
}

foreach ($html->find('div.blockshadow iframe') as $key => $a) {
    $linkUrl = $a->src;
    $wpdb->insert(
            $table_name, array(
        'Idioma' => $lang,
        'Calidad' => ucwords("HDRIP"),
        'Enlace' => $linkUrl,
        'PID' => $return['ID'],
        'Tipo' => '3',
            )
    );
}

If you do not plan to split up your data into multiple tables and want to keep it all in one column, you can use json_encode / serialize .

Which one of both you choose is pretty much up to you, but stay consistent.

When you read out your data, just use json_decode / unserialize and you get back your initial array.

Something like:

   $data = json_encode([
       'Idioma' => $lang,
       'Calidad' => ucwords("HDRIP"),
       'Enlace' => $linkUrl,
       'PID' => $return['ID'],
       'Tipo' => '3',
   ]);

   $wpdb->insert($table_name, $data);

And for reading, you first want to select the data from your table like normal, but before using it, you have to json_decode / unserialize the column which yields this data.

Convert the array into string, using the implode function and also do check if the value is empty or not, something like this.

$newLang = "";

if(!empty($lang))
{
   $newLang = implode(',',$lang);
}

And use the $newLang variable for the database, also inside the foreach loop you want to insert all the values present in the array, then use the above way, if you want specific values with each loop, then use $newLang[$key] .

Hope this helps.

PS: You can't insert array directly into table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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