Update Full Array values in one column - php

I have a table with blog column in it and i want to add values from a array, my problem is that i need to insert one full array value in one column. Here is what i am trying ...
foreach($title1->find('tr') as $song){
$name_a[] = $song->plaintext.'<br>';
}
and trying to enter this array in column
for($i=0, $count = count($name_a);$i<$count;$i++) {
$lyrics = array_push($name_a[$i]);
$songs_data_update = array(
'lyrics' => $lyrics,
'songs' => $song_name
);
try {
$STH = songs_data_update();
$STH->execute($songs_data_update);
}catch (PDOException $DBH){
die($DBH->getMessage());
}
}
i know this is wrong ... and its not working ... i want to add '< br >' in end of each row thats the reason i am making array to this. So how can i do this ... full array goes in one column

Use implode. E.g.
$lyrics = join('', $lyrics);
turns the Array $lyrics into a string consisting of all its elements concatenated.

Related

Illegal string offset 'Name' Error

I am trying to access the name field in the database through this code. But everytime it gives me "Illegal string offset error". I don't know the correct syntax needed inside second bracket of product_array.
$qry = "SELECT * FROM Products ORDER BY Product_Id ASC";
$result = mysqli_query($con,$qry);
$product_array = (array) $result->fetch_assoc();
mysqli_close($con);
if (!empty($product_array)) {
foreach($product_array as $key=>$value){
echo $product_array[$key]['Name'];
}
}
?>
fetch_assoc() only fetches one row - iterating this row gives you column values (single string, number, ...). And you try to access Name index on such value, which leads to error.
You need to use $product_array = $result->fetch_all(MYSQLI_ASSOC); to get iterate all results.
Also instead of $product_array[$key]['Name'] you can use $value['Name'].
mysqli::fetch_assoc does not return a multi dimensional array rather a 2d row from the database (only one), so, if you have the following fields / data for example;
name abc
date 01-01-2018
Using a query and fecth_assoc will return an array such as;
[ 'name' => 'abc', 'date' => '01-01-2018' ]
So, using foreach, you can do the following;
foreach ($product_array as $key => $value)
{
// Example printing; name = abc
echo "{$key} = {$value}";
// Example prining; abc
echo $product_array[$key];
}

Codeigniter DB query php

I have the following codes:
$spaces=0;
$str="bike car ";
for($i = 0; $i < strlen($str); $i++)
{
if($str[$i]==" ")
{
$spaces+=1;
}
}
$names=explode(" ",$str);
The above code is used to split the words inside the string. How do i do a db query wherein i get the id of the names(words in the string i separated).
Assuming, i have a price table
The table has lets say 2 cols, item name and id
How do i parse DB query wherein i need to get the ids of the item names listed.
I guess you want to get the id of exploded $name simply you can use $this->db->where_in()
example :
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')
See the documenation here : Where In Query
So the next line of your code maybe seems like this one :
$names = explode(" ",$str);
$this->db->select('id')
->where_in('your_table_name',$names);
$query = $this->db->get();
$result = $query->result_array();
then you can use the $result by
foreach($result as $r){
echo 'The id is :'.$r['id'];
}
You can simple use array_keys and array_values to traverse you array keys and values
//sample array
Array
(
[1334] => Face Towel
[4552] => White Socks
[3442] => Lotion
[6643] => Pants
[4432] => foobar
[5532] => bar
)
$items = implode(',',array_values($array)); //will get the array values
$itemid = implode(',',array_map('intval',array_keys($array))); //will get the array keys
$this->db->where_in('items', $items);
// where items IN ('Face Towel','White Socks','Lotion','pants','foobar','bar')
$this->db->where_in('itemid', $itemid);
// where itemid IN (1334,4552,3442,6643,4432,5532)
Note that i used array_map to loop through each keys and cast every key as integer.

Store Session Array in Database

I have the array-ed session....
$_SESSION['Names'] = array (11,15,26);
$_SESSION['Location'] = array (35,42,10);
and I want to store them in my database...
$que = "Insert into tblpeople (DateTimePosted, first, second, third) VALUES(now(),'$_SESSION['Names'][0], $_SESSION['Location'][0])','$_SESSION['Names'][1], $_SESSION['Location'][1])','$_SESSION['Names'][2], $_SESSION['Location'][2])')";
$exec = mysql_query($que);
After Saving, my database (tblpeople) shows the following values:
DateTimePosted: 2014-01-03 16:23:02
first: Array[0],Array[0]
second: Array[1],Array[1]
third: Array[2],Array[2]
Instead, I want my output to be...
DateTimePosted: 2014-01-03 16:23:02
first: 11,35
second: 15,42
third: 26,10
What's wrong?
To expand multidimensional arrays in a string, you need to wrap them in curly braces:
$que = "Insert into tblpeople (DateTimePosted, first, second, third)
VALUES(now(),
'{$_SESSION['Names'][0]}, {$_SESSION['Location'][0]}',
'{$_SESSION['Names'][1]}, {$_SESSION['Location'][1]}',
'{$_SESSION['Names'][2]}, {$_SESSION['Location'][2]}')";
You also had some extra parentheses in the values.
However, this seems like a pretty strange way to store data into a database. Why do you have two values separated by commas in each column, rather than splitting each into separate columns? And why are you storing array elements into different columns, rather than using separate tables with each value in a row?
use this function
$x=serialize($_SESSION['Names']);
it return a string that you can save any where
and this function reverse it
$_SESSION['Names']=unserialize($x);
Try this
<?php
session_start();
$_SESSION['Names'] = array (11,15,26);
$_SESSION['Location'] = array (35,42,10);
$refNumbers = $_SESSION['Names'];
$partIds = $_SESSION['Location'];
$combined = array();
foreach($refNumbers as $index => $refNumber) {
if(!array_key_exists($index, $partIds)) {
throw OutOfBoundsException();
}
$combined[] = array(
'Names' => $refNumber,
'Location' => $partIds[$index]
);
}
print_r($combined);
$combine1 = implode(",",$combined[0]);
$combine2 = implode(",",$combined[1]);
$combine3 = implode(",",$combined[2]);
$que = "insert into tblpeople (DateTimePosted, first, second, third) VALUES(now(),'$combine1','$combine2','$combine3')";
//$exec = mysql_query($que);
?>

array to string conversion error, need to explode and then implode

I want to explode an array, read each value and print them back in an array...
I dont understand where i am getting wrong. Please help me..this is my code..
I am getting an array to string conversion error
$query="SELECT categories FROM shops";
$result = mysql_query($query);
while($column = mysql_fetch_assoc($result)){
$categories=explode(",",$column['categories']);
foreach($categories as $value){
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
array_push($shops_list,$name_column);
}
}
echo implode(",",$shops_list);
$shop_list is not defined, before using it in this line array_push($shops_list,$name_column);. And, this line
array_push($shops_list,$name_column);
needs to be, as you need to mention the key name,
array_push($shops_list,$name_column['name']); //or better
$shop_list[] = $name_column['name'];
Several issues:
$name_column = mysql_fetch_assoc($name);
$name_column = $name_column['name'];
name_column is an array.
shops_list is never initialized.
You should use [] instead of array_push.
The other guys hit it on the nose, but when you did your array push on $name_column, since $name_column is an array, you end up with:
Array
(
[0] => Array
(
[name] => boo
)
)
Obviously doing an implode on that is going to not work.
That being said, what you really need to do here is not keep your category mappings as a comma delimited string in the database. Standard DB architecture dictates you use a mapping table.
Table shops
Table categories
Table shop_category_map that has shop_id and category_id
use group_concat to retrieve values. and after getting the result, use them directly for searching. like
$result_array = explode(",",$row['category']);
foreach($result_array as $ra)
{
//sql command. fetch here.
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
$shops_list[] = $name_column;
}
try else go for better solution
// explode an array and then implode until a particular index of an array
$a = '192.168.3.250';
$b = explode('.',$a);
$ar = array();
for($i=0;$i<=2;$i++)
{
array_push($ar,$b[$i]);
}
$C = implode($ar,'.');
print_r($C);

Two dimensional associative array in PHP

In my code I'm getting data (three columns) from a sql db and I want to store the rows in an associative PHP array. The array must be multi-dimensional because I want to use the row id from the database as a key so that i can fetch values like this:
$products["f84jjg"]["name"]
$products["245"]["code"]
I've tried using the following code but it doesn't work:
while ($row = mysql_fetch_row($sqlresult))
{
$products = array($row[0] => array(
name => $row[1],
code => $row[2]
)
);
}
Also, how should I reference the key if it is taken from a variable? What I want to do is:
$productName = $products[$thisProd]["name"];
Will this work?
This should do it, assuming row[0]'s contents is a unique identifier (else you could override a row):
while($row = mysql_fetch_row($sqlresult)) {
$products[$row[0]] = array(
'name' => $row[1],
'code' => $row[2]
);
}
You need to put quotes around the array keys, and you were creating an array of array of arrays.
Also note you could use mysql_fetch_assoc instead of mysql_fetch_row, which would give you the array keys as the column names, which would make this much easier/cleaner:
while($row = mysql_fetch_assoc($sqlresult)) {
$products[$row['myidcolumn']] = $row;
}
After you do this, the code you described would work.

Categories