implode or explode mysql_fetch_array in php - php

Hi guys.
I'm currently try to make an mysql query than take the results and use them in an another query. So I thought I'm calling my database and use mysql_fetch_array and than implode it do insert , so I can use it in an another query. I read here many questions about this and based on the questions i wrote my own piece of code but I'm getting this error:
Warning: array_values() expects parameter 1 to be array, string given in /var/www/html/lager_management/warenkorb.php on line 107
Warning: implode(): Invalid arguments passed in /var/www/html/lager_management/warenkorb.php on line 108
Here is the piece of code what is going wrong I can't explain myself and I know mysql is old and I should use myqli
$sql3 = "SELECT `Index` FROM lm_Warenkorb;";
$result3 = mysql_query($sql3);
while($resultarray3 = mysql_fetch_array($result3))
{
$anfrage = array();
$anfrage = $resultarray3['Index'];
$anfrage = implode(", ", $anfrage);
$sql2 = "SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` FROM `lm_Artikel` WHERE `Index` IN (".$anfrage.");";
}
The table lm_Warenkorb looks like this:
Index:
10
2
6

I think you could do it using one query with nested SELECT:
$sql3 = "
SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort`
FROM `lm_Artikel`
WHERE `Index` IN (
SELECT `Index` FROM lm_Warenkorb
)";
$result3 = mysql_query($sql3);
while($resultarray3 = mysql_fetch_array($result3)) {
// handle the results
}

you use mysql_fetch_array($result) in a while loop, which is perfectly right.
But this obviously will only return one row of your table from database and not the whole column.
therefore $resultarray3['Index']; returns the value of Index column of your first table row, which is not an array.

Try this
$anfrage = array();
while($resultarray3 = mysql_fetch_array($result3))
{
$anfrage[] = $resultarray3['Index'];
}
if(count($anfrage) > 0) {
$anfrage = implode(",", $anfrage);
$sql2 = "SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` FROM `lm_Artikel` WHERE `Index` IN (".$anfrage.");";
}

$sql3 = "SELECT `Index` FROM lm_Warenkorb;";
$result3 = mysql_query($sql3);
$data = array(0);
while($resultarray3 = mysql_fetch_assoc($result3))
{
$data[] = $resultarray3['Index'];
}
$sql2 = "SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` FROM `lm_Artikel` WHERE `Index` IN (".implode(',', $data).");";
echo $sql2;

Related

Array to string conversion in mysql while loop

Following is my code,
$result1 = "SELECT emp_id FROM employee where manager_id=".$userID;
$array = mysql_query($result1);
$cnt = 0;
while ($row = mysql_fetch_array($array)) {
"emp_id: " . $row[0];
$myArrayOfemp_id[$cnt] = $row[0];
$cnt++;
}
var_dump($myArrayOfemp_id);
$sql = "SELECT emp_id FROM emp_leaves WHERE emp_id='$myArrayOfemp_id' ORDER BY apply_date DESC";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
When I'am trying to use $myArrayOfemp_id variable in $sql query, It shows that error:
Array to string conversion in..
How can I fix it?
You are trying to convert an array into a string in the following line:
$sql = "SELECT emp_id FROM emp_leaves
WHERE emp_id='$myArrayOfemp_id' ORDER BY apply_date DESC";
$myArrayOfemp_id is an array. That previous line of code should be changed to:
$sql = "SELECT emp_id FROM emp_leaves
WHERE emp_id={$myArrayOfemp_id[0]} ORDER BY apply_date DESC";
I placed 0 inside {$myArrayOfemp_id[0]} because I'm not sure what value want to use that is inside the array.
Edited:
After discussing what the user wanted in the question, it seems the user wanted to use all the values inside the array in the sql statement, so here is a solution for that specific case:
$sql = "SELECT emp_id FROM emp_leaves
WHERE ";
foreach ($myArrayOfemp_id as $value)
{
$sql .= " emp_id={$value) || ";
}
$sql .= "1=2";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
$sql = "SELECT emp_id FROM emp_leaves WHERE emp_id in
(SELECT GROUP_CONCAT(emp_id) FROM employee where manager_id=".$userID.")
ORDER BY apply_date DESC";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
just change your query like above might solve your problem.
you can remove following code now. :)
$result1 = "SELECT emp_id FROM employee where manager_id=".$userID;
$array = mysql_query($result1);
$cnt = 0;
while ($row = mysql_fetch_array($array)) {
"emp_id: " . $row[0];
$myArrayOfemp_id[$cnt] = $row[0];
$cnt++;
}
var_dump($myArrayOfemp_id);

What is wrong with my PHP deduper for MySQL?

I am trying to de-duplicate entries in one of my MySQL tables but I keep getting the same error.
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\Inetpub\vhosts\myexamplewebsite.com\httpdocs\duplicate\index.php on line 25
What am I doing wrong please?
<?php
$dedupe=mysqli_connect("localhost","user","pass","database");
$result = mysqli_query($dedupe,"SELECT * FROM `videos` WHERE `dupe`=0 order by RAND() ");
while($row = mysqli_fetch_array($result))
{
$vod_index = $row['index'];
$vod_video_name = $row['video_name'];
$vod_vidstart = $row['vidstart'];
$vod_providerid = $row['providerid'];
$vod_dupe = $row['dupe'];
$result2 = mysqli_query($dedupe,"SELECT * FROM `videos` WHERE `index` != '$vod_index';
AND `dupe`='0'
AND `video_name` = '$vod_video_name'
AND `vidstart` = '$vod_vidstart'
AND `providerid` = '$vod_providerid'
AND `index` != '$vod_index'
");
while($row2 = mysqli_fetch_array($result2))
{
$vod_index2 = $row2['index'];
$vod_video_name2 = $row2['video_name'];
$vod_vidstart2 = $row2['vidstart'];
$vod_providerid2 = $row2['providerid'];
$vod_dupe2 = $row2['dupe'];
mysqli_query($dedupe,"UPDATE `videos` set `dupe`=1
WHERE `index`='$vod_index2' ");
{
echo("Error description: " . mysqli_error($recordcon));
}
mysqli_query($dedupe,"INSERT INTO deduped (index,videos_index)
VALUES ('NULL','$vod_index2')");
}
}
mysqli_close($dedupe);
?>
Please note: index is the primary key for the table.
I would prefer to fix this method than start another if possible as I wrote this as a simpler one for me to understand than examples I was finding that other people have written.
Any help is appreciated.
You have an unexpected semicolon in your query, try it like this:
$result2 = mysqli_query($dedupe,"SELECT * FROM `videos` WHERE `index` != '$vod_index'
AND `dupe`='0'
AND `video_name` = '$vod_video_name'
AND `vidstart` = '$vod_vidstart'
AND `providerid` = '$vod_providerid'
AND `index` != '$vod_index'
");

Pass column value from Select query to another query for insertion in PHP

I was thinking of accomplishing the following as a PHP multi_query. But I'm trying to figure out how to pass the column value from the select query to the insert and update queries.
$query = "SELECT tbl_links.link, link_id
FROM tbl_links
INNER JOIN tbl_items ON tbl_links.item_id = tbl_items.item_id
WHERE tbl_items.item_name like '".$items_name[$counter]."'
AND NOT EXISTS (
select link_id
from tbl_clickedlinks
where tbl_clickedlinks.link_id = tbl_links.link_id
AND tbl_clickedlinks.cust_id = '$items_custID[$counter]'
)
limit 0, 1;" ;
$query .= "INSERT INTO tbl_claimedlinks (cust_id, link_id, claim_time) VALUES ('$items_custID', $row['link_id'], NOW()) ;";
$query .= "UPDATE tbl_links SET click_count = click_count+1 where link_id = '$linkID' ;";*/
Problem is, I'm not sure how to pass the link_id value to the other queries. So I'm thinking I might have to rearrange the queries into one, but again, I'm just not sure how to pull that off.
Anyone got any suggestions?
You need to execute select query 1st then use its output to execute 2nd & 3rd query.
$query = "SELECT tbl_links.link, link_id
FROM tbl_links
INNER JOIN tbl_items ON tbl_links.item_id = tbl_items.item_id
WHERE tbl_items.item_name like '".$items_name[$counter]."'
AND NOT EXISTS (
select link_id
from tbl_clickedlinks
where tbl_clickedlinks.link_id = tbl_links.link_id
AND tbl_clickedlinks.cust_id = '$items_custID[$counter]'
)
limit 0, 1;" ;
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$query2 = "INSERT INTO tbl_claimedlinks (cust_id, link_id, claim_time) VALUES ('$items_custID', $row['link_id'], NOW()) ;";
$query3 = "UPDATE tbl_links SET click_count = click_count+1 where link_id = '$linkID' ;";*/
mysql_query($query2);
mysql_query($query3);
}

Output mysql result as an array of the form (column name => possible values for column name)

I have database such as
I want to create an associative array such that each att_name value is associated with its possible values from att_value:
array('att_name' => array('att_value_1', 'att_value_2', 'att_value_3'))
What is the best way to achieve this?
While it is easily possible to do this simply by selecting the results you want and iterating them in PHP to create the data structure you want, you could sub some of the work out to MySQL with GROUP_CONCAT():
$query = "
SELECT att_name, GROUP_CONCAT(att_value SEPARATOR ',') AS values
FROM table_name
GROUP BY att_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']] = explode(',', $values);
}
print_r($array);
Of course, this only works if your values will never contain the character (or sequence of characters) you use for the SEPARATOR in the MySQL query, so the safer pure-PHP way would be:
$query = "
SELECT att_name, att_value
FROM table_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']][] = $row['att_value'];
}
print_r($array);
Try below:
$sql = "SELECT * from tablename";
$result = mysql_query($sql,$con);
$final_array=array();
while ($row = mysql_fetch_object($result))
{
$final_array[$row->att_name][0]=$row->att_value_1;
$final_array[$row->att_name][1]=$row->att_value_2;
....
....
}
This way :
SELECT
item,
att_name,
GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value
FROM
table
GROUP BY
att_name
Will give you something like that :
item att_name att_value
-----------------------------
books height 150 mm<!>250 mm
books price rs:20<!>Rs:20
books size 15 pg<!>30 pg<!>60 pg
books width 300 mm<!>400 mm
You have to explode the result from att_value by a <!>. I use this <!> so it highly impossible to have a value inside att_value with this. If you think you would someday use this, take another separator. Example : [{--}], _SEPARATOR_, [_-CUT-_], etc. Something you are sure at 100% you won't use a choice but always as a separator to split the text.
So example :
$SQL = 'SELECT item, att_name, GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value FROM table GROUP BY att_name';
$Query = mysql_query($SQL) or die('MySQL Error : '.mysql_error());
while($Assoc = mysql_fetch_assoc($Query)){
$Assoc['att_value'] = ($Assoc['att_value'] != '' ? explode('<!>', $Assoc['att_value']) : NULL);
print_r($Assoc);
}

MySQL returns only one row

I have this simple PHP code:
$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5");
$query2 = mysql_fetch_assoc($quer);
print_r($query2);
It only returns this:
Array ( [title] => Kill Bill Vol 1. [url_title] => kill_bill_vol_1 )
I have 3500+ rows in the table, and running the SQL in PhpMyAdmin works perfectly.
$query = mysql_query("SELECT `title`,
`url_title`
FROM `fastsearch`
WHERE `tags`
LIKE '%$q%'
LIMIT 5");
while ($row = mysql_fetch_assoc($query)) {
print_r($row);
}
You misspelled $query in your example
mysql_fetch_assoc() will return a row each time it is called, and FALSE when out of rows. Use that to your advantage, by assigning a variable to it in the condition. Within the while() loop, $row will be the current row.
Right, you are not fetching the results properly.
mysql_fetch_assoc() only returns one row at a time. Use a loop to read all rows.
$query = mysql_query("SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5");
$resultSet = array();
while ($cRecord = mysql_fetch_assoc($query)) {
$resultSet[] = $cRecord;
}
As documentation http://php.net/manual/en/function.mysql-fetch-assoc.php states:
mysql_fetch_assoc — Fetch a result row as an associative array
So if you want to iterate over result you have to use a loop e.g.:
while ($row = mysql_fetch_assoc($result)) {
echo $row["title"];
echo $row["url_title"];
}
mysqli_fetch_assoc() is functions which is fetching multiple records
and displaying through print_r().
$query = "SELECT `title`, `url_title` FROM `fastsearch` WHERE `tags` LIKE '%$q%' LIMIT 5";
$result = mysqli_query($conn,$query);
while(null ! == ($query = mysqli_fetch_assoc($result))){
print_r($query);
}
the method fetch_assoc() returns one row, you need to loop with it

Categories