PHP Simple HTML DOM Parser array to database - php

So the problem is, when uploading to mysql the database is only uploading the last value in the array.
if (substr($avsnitt["serier"], 0, 16) === 'http://random'){
// Create DOM from URL or file
$html = file_get_html($avsnitt["serier"]);
$array_title = array();
$array_link = array();
foreach($html->find('div[class=entry]') as $element){
foreach ($element->find('a') as $text) {
$array_title[] = $text->plaintext;
}
foreach ($element->find('a') as $test) {
$array_link[] = $test->href;
}
$count_name = count($array_title);
for($i=0; $i<$count_name; $i++){
$_array_title = mysql_escape_string($array_title[$i]);
$_array_link = mysql_escape_string($array_link [$i]);
print_r($_array_title);
print_r($_array_link);
$sql2 = "INSERT INTO episodes (name, ID, link) VALUES ('" . #$_array_title. "','" . #$avsnitt["ID"] . "', '" . #$_array_link . "');";
mysqli_query($CON, $sql2);
}
}
}
i'm new to php mysql so i dont relly know how arrays is uploaded to mysql, fast answers will be appreciated thanks.

I think, your database-field "link" is type string.
You want to insert your variable $_array_link, witch is type array.
So try serialize($_array_link) to "convert" array to string.
I think, the # are not nessessary, without it is better to read.
$sql2 = "INSERT INTO episodes (name, ID, link)
VALUES ('" . #$_array_title. "','" . #$avsnitt["ID"] . "', '" . serialize($_array_link). "');";
Later, you want to use the variable from the database. So after you SELECT your data, use unserialize() to get the array back.

problem was the database ID was primery key only allowing one withe a specific ID

Related

Create a Dynamic insert statement - PHP - Mysql

I have a form which has multiple drop downs (16) speed[] and some other fields
The data from the dropdown boxes has to be inserted into a Mysql table
What I did is I took the count count($_POST["speed"]);and then loop through until the end of the speed array.
The problem is:
If Anyone of the dropdown is not selected it returns "-1", if used `($_POST["speed"][$i]!="-1")for that but it does not compare and goes into the IF loop
The Insert Query is not a valid not sure how to append the extra commas
$sql when printed
INSERT INTO mytablename (w_name,wtype,speed1,speed2, speed3, speed4, speed5, speed6, speed7, speed8, speed9, speed10, speed11, speed12, speed13, speed14, speed15, speed16, coach_id) VALUES ('name', '', ''-1''800''-1''-1''200''-1''-1''-1''-1''-1''-1''-1''-1''-1''-1''200'', '208')
My PHP code
$itemCount = count($_POST["speed"]);
$itemValues=0;
$query = "INSERT INTO mytablename (w_name,wtype,speed1,speed2, speed3, speed4, speed5, speed6, speed7, speed8, speed9, speed10, speed11, speed12, speed13, speed14, speed15, speed16, coach_id) VALUES ";
$bldSpltString="";
$queryValue = "";
for($i=0;$i<$itemCount;$i++) {
if(($_POST["speed"][$i]!="-1") || !empty($_POST["speed"][$i])) {
$bldSpltString .= "'" . $_POST["speed"][$i] ."'";
}
}
$queryValue .= "('" . $wkout . "', '" . $wtype . "', '" . $bldSpltString . "', '" .$_SESSION['id']."')";
$sql = $query.$queryValue;
echo $sql;
exit;
I would do something like this:
<?php
function dynamicInsert($table_name, $assoc_array){
$keys = array();
$values = array();
foreach($assoc_array as $key => $value){
$keys[] = $key;
$values[] = $value;
}
$query = "INSERT INTO `$table_name`(`".implode("`,`", $keys)."`) VALUES('".implode("','", $values)."')";
echo $query;
}
dynamicInsert("users", array(
"username" => "Test User",
"password" => "Password123"
));
?>
WARNING: This code is not secure, I would run a mysql_real_escape_string and any other necessary sanitation on the variables being sent to mysql. I would also steer clear of allowing this script to run on anything public facing as a dynamic insert could allow for huge security risks!

Sending ARRAYS to table as individual submissions

I'm new to PHP. I'm trying to split up my array (done successfully) and submit them as individual submisions into my MYSQL Table (via FOR loops). However, using the code below, it only submits the LAST object in the array. And thus defeats the whole purpose of the desired function. Can anybody show me a way to avoid this?
$directives = "(John Doe, Directive, Time)(Jane Doe, Directive2, Time2)";
$action = explode("(" ,str_replace (")","",$directives));
for ($i = 0; $i < count($action); ++$i){
$newdata = explode("," , $action[$i]);
$name = $newdata[0];
$namesplit = explode(" " , $name);
$actiondo = $newdata[1];
$date = $newdata[2];
$sqlaction="INSERT INTO TABLE (Firstname, lastname, Description, Action, date)
VALUES
('$namesplit[0]','$namesplit[1]',' Directive','$actiondo','$date')";
}
You are overwriting your query in $sqlaction with each loop iteration, thus this is not useful.
You also don't need a query for each row. You can build up a query that would allow insert of all rows with a single query. Something like this:
$query = 'INSERT INTO TABLE (Firstname, lastname, Description, Action, date)
VALUES ';
for ($i = 0; $i < count($action); ++$i){
$newdata = explode("," , $action[$i]);
$name = $newdata[0];
$namesplit = explode(" " , $name);
$actiondo = $newdata[1];
$date = $newdata[2];
$query .= "('" . $namesplit[0] . "','" . $namesplit[1] . "'Directive','" . $actiondo . "','" . $date . "'),";
}
$query = rtrim(',', $query);
// not shown - execute query using $query
First, you would have to put the code that actually puts stuff in the database inside the loop in order to do lots of individual submissions. All your code currently does is just set the same string over and over. That's why only the last one gets inserted.
Second, why don't you just do one insert? You can have multiple values parentheses, you know. Like this:
VALUES (x, y, z), (x2, y2, z2), (x3, y3, z3)
Third, your design is just asking for trouble because you're making so many assumptions about your data. Imagine that there's a person like "James Earl Jones" in your list. Here's how it would go:
$namesplit = explode(" ", 'James Earl Jones');
echo $namesplit[0]; // = James
echo $namesplit[1]; // = Earl
Oops, now his name is just "James Earl."
To avoid this kind of thing, you have to check the data carefully before inserting it, and you really need to think about what might happen if there are extra commas or spaces every time you do those explodes.

Form With Unlimited Fields

I have a form that has an [Add Fields] option making it possible to add virtually unlimited Item Numbers and Descriptions.
These fields are named: item[] and desc[] (brackets for arrays).
My question is, how would I submit this information with PHP and MySQL so that each row (item and description) is submitted as it's own row in the database?
I've tried multiple methods like submitting item[0] and desc[0] together with no avail :(
Thanks for all of your help in advance!
EDIT: Below is what I've been trying to use... (Sorry, not that great with arrays...)
$count = 0
foreach ($_POST['item'] as $item) {
$query = "INSERT INTO items (item, desc) VALUES ('" . $item[$count] . "', '" . $_POST['desc'][$count] . "')";
// Script simplified as it is quite complex.
if ($query_result) {
$count++;
}
}
you can loop through any one of the input field using foreach loop and then access other fields.
foreach($_POST['item'] as $key => $item){
//your code
$desc = $_POST['desc'][$key];
}
EDIT : as per your code script will be like
$count = 0
foreach ($_POST['item'] as $key => $item) {
$query = "INSERT INTO items (item, desc) VALUES ('" . $item . "', '" . $_POST['desc'][$key] . "')";
// Script simplified as it is quite complex.
if ($query_result) {
$count++;
}
}
To further help you out, I might suggest the following.
Name your fields like so:
line[1][item]
line[1][desc]
line[2][item]
line[2][desc]
etc...
Then in PHP the data will make more 'sense' when viewing it:
<?php
$count = 0;
foreach ($_POST['line'] as $line => $vals) {
$item = $vals['item']; /* do some kind of input validation here */
$desc = $vals['desc']; /* do some kind of input validation here */
/* if no errors, continue */
$sql = "INSERT INTO `items` (`item`,`desc`) VALUES ('$item', '$desc')";
if (mysql_query ($sql)) {
$count++;
}
}
?>
I find this method to be more flexible. Just my two cents.
Luke

Change Static SQL update to dynamic based on changing column names

Ok, I asked a question last night and received a number of really great responses. Since that was my first time using StackOverflow I was really pleased.
I'm hoping you guys can help with a new one. Hopefully, down the road, I'll be able to repay the favor to some NEW newbies.
I have the following code in a php file:
$sql = "";
$now=date("Y-m-d h:i:s");
$updatedRecords = $json1->{'updatedRecords'};
foreach ($updatedRecords as $value){
$sql = "update `acea` set ".
"`ACEA_A1`='".$value->ACEA_A1 . "', ".
"`ACEA_A2`='".$value->ACEA_A2 . "', ".
"`ACEA_A3`='".$value->ACEA_A3 . "', ".
"`ACEA_A4`='".$value->ACEA_A4 . "', ".
"`ACEA_A5`='".$value->ACEA_A5 . "', ".
"`ACEA_B1`='".$value->ACEA_B1 . "', ".
"`ACEA_B2`='".$value->ACEA_B2 . "', ".
"`ACEA_B3`='".$value->ACEA_B3 . "', ".
"`ACEA_B4`='".$value->ACEA_B4 . "', ".
"`ACEA_B5`='".$value->ACEA_B5 . "', ".
"`ACEA_E1`='".$value->ACEA_E1 . "', ".
"`ACEA_E2`='".$value->ACEA_E2 . "', ".
"`ACEA_E3`='".$value->ACEA_E3 . "', ".
"`ACEA_E4`='".$value->ACEA_E4 . "', ".
"`ACEA_E5`='".$value->ACEA_E5 . "', ".
"`ACEA_E7`='".$value->ACEA_E7 . "' ".
"where `acea_id`=".$value->acea_id;
if(mysql_query($sql)==FALSE){
$errors .= mysql_error();
}
}
The "ACEA_XX" portions relate to columns in the "acea" database table (obviously), but the programmer set them statically. Unfortunately, these columns need to be added to periodically, with new columns being created related to the new ACEA specs that are introduced.
As a result, this code becomes outdated.
Without having to go in and update this code each time I add a new column, how can I redesign this code so that it updates itself dynamically to include the new columns? I've been trying all morning to make it work, and I can set it so that I can dynamically insert the actual column names into the update statement, but, I can't seem to dynamically grab the associated values dynamically (and I think my method for grabbing and inserting the column names is a little convoluted).
My actual database table columns are currently:
acea_id ACEA_A1 ACEA_A2 ACEA_A3 ACEA_A4 ACEA_A5 ACEA_B1 ACEA_B2 ACEA_B3 ACEA_B4 ACEA_B5 ACEA_E1 ACEA_E2 ACEA_E3 ACEA_E4 ACEA_E5 ACEA_E6 ACEA_E7 ACEA_E9 oil_data_id
The first and last columns will never change and will continue to be the first and last columns. Any new columns will be added somewhere in between, but not necessarily immediately preceding the "oil_data_id" column.
I've tried revising the code numerous ways in order to properly grab the values, but just can't make it work.
Anyone have a concise modification to the code to do what I want? It would be greatly appreciated.
Seems like Doug Kress' method spits some errors out so here is my shot:
$errors = array();
foreach($json1->updatedRecords as $record)
{
$fields = array();
foreach($record as $field => $value)
{
if(substr($field, 0, 5) === 'ACEA_')
{
$fields[] = $field.' = '.mysql_real_escape_string($value);
}
}
// Check if there are any fields set to be updated.
if(isset($fields[0]))
{
// I'm assuming $record->acea_id is an integer. If not,
// replace '%d' with '%s'.
$sql = "UPDATE `acea` SET %s WHERE `acea_id` = '%d';";
$sql = sprintf($sql, implode(',', $fields), $record->acea_id);
if(mysql_query($sql) === false)
{
$errors[] = mysql_error();
}
}
}
First, I would highly recommend making that into a separate table (turning the data 'sideways', if you will). Assuming that's not feasible:
$sql = "";
$updatedRecords = $json1->{'updatedRecords'};
foreach ($updatedRecords as $values){
$flist = array();
$params = array();
foreach ($values as $key => $value) {
if (preg_match('/^ACEA_[A-Z]+\d+$/', $key)) {
$flist[] = $key .'="%s"';
$params[] = mysql_real_escape_string($value);
}
}
$sql = "update `acea` set ". implode(', ', $flist) .
"WHERE `acea_id`='%s'";
$params[] = mysql_real_escape_string($value->acea_id);
$sql = sprintf($sql, $params);
if(mysql_query($sql)==FALSE){
$errors .= mysql_error();
}
}

insert multiple rows into database from arrays

i need some help with inserting multiple rows from different arrays into my database.
I am making the database for a seating plan, for each seating block there is 5 rows (A-E) with each row having 15 seats.
my DB rows are seat_id, seat_block, seat_row, seat_number, therefore i need to add 15 seat_numbers for each seat_row and 5 seat_rows for each seat_block.
I mocked it up with some foreach loops but need some help turning it into an (hopefully single) SQL statement.
$blocks = array("A","B","C","D");
$seat_rows = array("A","B","C","D","E");
$seat_nums = array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15");
foreach($blocks as $block){
echo "<br><br>";
echo "Block: " . $block . " - ";
foreach($seat_rows as $rows){
echo "Row: " . $rows . ", ";
foreach($seat_nums as $seats){
echo "seat:" . $seats . " ";
}
}
}
Maybe there's a better way of doing it instead of using arrays?
i just want to avoid writing an SQL statement that is over 100 lines long ;)
(im using codeigniter too if anyone knows of a CI specific way of doing it but im not too bothered about that)
try
<?php
$blocks = array("A","B","C","D");
$seat_rows = array("A","B","C","D","E");
$seat_nums = array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15");
foreach($blocks as $block){
foreach($seat_rows as $rows){
foreach($seat_nums as $seats){
$querys[] = "('" . $block "','" . $rows . "', '" . $seats . "' )";
}
}
}
$query_inserts = join ( ", ", $querys );
$query = "
INSERT INTO
table
( block, rows, seats )
VALUES
" . $query_inserts . "
";
mysql_query ($query);
?>
One solution is to use prepared statements:
$pdo = new PDO('mysql:dbname=mydb', 'myuser', 'mypass');
$stmt = $pdo->prepare('INSERT INTO seats
(seat_id, seat_block, seat_row, seat_number)
VALUES (?,?,?,?);
');
foreach (...) {
$stmt->execute(array($seat_id, $seat_block, $seat_row, $seat_number));
}

Categories