Error: Array to string conversion error - php

Firstly I am randomly selecting the ID from my table. That part works fine but the next part doesn't. The next part is selecting the ID's row, e.g. if the ID is 6, then it should select all the fields related to 6.
my table is like this:
------------------------------
|ID|Name|Email |Password|
------------------------------
|1 |Amy |H#gmail.com|jaaaaaaa|
------------------------------
|2 |Bob |1#gmail.com|haaukanm|
------------------------------
|3 |Bill|aa#mail.com|fsoji443|
------------------------------
This is my code:
<?php
include('connect.php');
//select a number between min id and max id
$v = "SELECT ID FROM `tblaccounts` ORDER BY RAND() LIMIT 1";
$result = mysqli_query($connection, $v);
$data2 = mysqli_fetch_array($result);
//var_dump($data2);
$c = "SELECT * FROM `tblaccounts` WHERE ID='$data2'";
$cresult = mysqli_query($connection, $c);
$data3 = mysqli_fetch_array($cresult);
var_dump($data3);
?>

The issue is here:
$c = "SELECT * FROM `tblaccounts` WHERE ID='$data2'";
here $data2 is not a single value, its an array and you are trying to compare it in WHERE like a string, that's why the error. Instead try $data2['id'] like:
$c = "SELECT * FROM `tblaccounts` WHERE ID='".$data2['ID']."'";
or
$c = "SELECT * FROM `tblaccounts` WHERE ID=".$data2['ID']; // Sinlge quote is not required if `ID` is `int`

Because your $data2 is an array, this is should work
include('connect.php');
//select a number between min id and max id
$v = "SELECT ID FROM `tblaccounts` ORDER BY RAND() LIMIT 1";
$result = mysqli_query($connection, $v);
$data2 = mysqli_fetch_array($result);
//var_dump($data2);
$c = "SELECT * FROM `tblaccounts` WHERE ID='".$data2['ID']."'";
$cresult = mysqli_query($connection, $c);
$data3 = mysqli_fetch_array($cresult);
var_dump($data3);

You are getting this error as you are comparing array in where clasue.
Your $data is an array like below
$data = array(
'ID'=>2
'Name'=>'Bob',
'Email'=>'1#gmail.com',
'Password'=>'haaukanm'
);// say record with id 2 is fecthed
So use $data['ID'] in your where clause

Related

i want to select a randomly data using php

I need help in selecting a random data from the table
Let's suppose There are 10 columns in my table but i want that if I hit the query sometime it will bring all data and sometime it will bring data only from 1 column and some time from the no 1 and no 2 column
How can I achieve this?
Thanks in advance
function selectAllInventoriesINGroup($conn,$groupname,$import_id)
{
$cgstSgst = explode('-', $groupname);
$sql = "SELECT * FROM stockitems WHERE generalid = '$import_id' AND cgst = '$cgstSgst[0]' AND sgst = '$cgstSgst[1]' ORDER BY RAND()";
$result = $conn->query($sql);
$jsonxx = mysqli_fetch_all ($result, MYSQLI_ASSOC);
return $jsonxx ;
}
I have tested this but it fetch the all the data from the database
<?php
$sql = "SELECT * FROM stockitems WHERE generalid = '$import_id' AND cgst = '$cgstSgst[0]' AND sgst = '$cgstSgst[1]' ORDER BY RAND()";
?>

get required result in sql

i have a sql database having two columns
1. id and 2. parent_id
i want to select all ids where parent_id=1 [let the results saved in X array] then,
select all the ids where parent_id in X[] [let the results saved in Y array] then... do the same upto 7 levels at last i want to sum all levels and get that sum in a variable name "number"
what i tried:
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id = ".$parent[id];
$result = mysqli_query($con, $sql);
$lv1 = mysqli_fetch_array($result);
then again
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id in ($lv1)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
and so on.... it may give me required result but it is too much code...
i want to the same by using a loop or something else... to shorten the code.
Your first query gets count(id) and then second query uses it to get results. It seems you have many flaws in your requirement to begin with.
However, for your question you can use sub-query like following
$sql = "SELECT count(id) as leadersearch
FROM `$database`.`$mem`
WHERE parent_id in (
SELECT id FROM `$database`.`$mem` where parent_id = ".$parent['id']."
)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
If you have many level nesting and you want to search records like this then you can consider functions:
function getLeader($parent_id){
$results = [];
$sql = "SELECT id as leadersearch FROM `$database`.`$mem` where parent_id in (".$parent_id.")";
$result = mysqli_query($con, $sql);
foreach($row = mysqli_fetch_array($result)){
$results[] = $row['id'];
}
return $results;
}
$leaders = [];
$ids = getLeader($parent['id']);
foreach($ids as $id){
$leaders[$id] = getLeader($id);
}

Show only the last result from mysql row

I have a table
id | field1 | field2 | ... | field[x-1] | field[x]
1 | val1 | val2 | ... | val[x-1] | val[x]
And I'm doing this search
for($i = 1; $i <= $x; $i++){
$getvalue = mysql_query("SELECT * FROM table WHERE id='1' AND field".$i." LIKE 'some_value%'")or die(mysql_error());
while($row = mysql_fetch_array($getvalue)){
$j=$i+1;
$val = $row['field'.$j.''];
}
}
Some values in the table (val[1-x]) will be the same but I need to get only the LAST value. Limit 1 doesn't seem to work.
Update.
Unfortunately as David suggested, I can't change the database. It has to be as it is. I have a text file (a settings dump from a sensor) that I insert it line by line into the db and do a check to see if there are any errors. Most check run ok but I have a few lines in that I need to choose only the last one to do the check.
I have about 10 lines like this
D?
String
R?
String
...
D?
String
R?
String
I'm interested in the last string after R?. I use explode () and each value checked that they are with in limits.
Using ORDER BY id DESC LIMIT 1:
To get last row (with highest=last=newest id), you should use this:
SELECT * FROM table ORDER BY id DESC LIMIT 1;
Your updated code (with mysqli_ extension) to get last row:
$query= mysqli_query("SELECT * FROM table ORDER BY id DESC LIMIT 1") or die (mysqli_error());
}
$lastRow = mysqli_fetch_row($query);
echo $lastRow['id']; //get the last id
Using MAX():
You also can do it using SQL MAX() function:
SELECT * FROM table WHERE id=(SELECT MAX(id) FROM table)
Managed to get it working as I need it by doing this:
for($i = 1; $i <= 250; $i++){
$getvalue = mysql_query("SELECT * FROM full_dump WHERE file_name='".$_FILES['datafile']['name']."' AND field_".$i." LIKE ' 100,%'")or die(mysql_error());
while($row = mysql_fetch_array($getvalue)){
$i_temp = $i;
}
}
if($i_temp != NULL){
$getvalue = mysql_query("SELECT * FROM full_dump WHERE file_name='".$_FILES['datafile']['name']."' AND field_".$i_temp." LIKE ' 100,%'")or die(mysql_error());
while($row = mysql_fetch_array($getvalue)){
$r = $row['field_'.$i_temp.''];
}
}

Add to array in comma separated values from database

my database table is named order. it has a row like order. I store values like this 1,2,3,4,5. Now i would like to add to array and from it out info..
I tried to do that but it is not working...
here is my code:
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
if want check print_r($array) Output
Array ( [0] => 1,23,4,5 )
this one is not working.. i think its supposed to be like this: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
FASTEST APPROACH
You need to use explode() function. Here is an example of it :
<?php
$array = array('0' =>'1,2,3,4,5');
$array = explode(',', $array[0]);
var_dump($array);
?>
Here is your updated code, to get array in that format.
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
$array = explode(',', $array[0]);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
Note this is solution which you are looking for. But it isn't recommended due to reason told to you as comment.
PROPER WAY TO HANDLE THIS
You should ideally normalize your Database so this kind of problem don't come even in future to you.
Here is a proposed table structure change, which you can consider, depending on your need & time.
Remove order column from your table. Add a new table named order_suborders as follows:
| COLUMN | TYPE |
|:-----------|------------:|
|parent_order| int |
| order_id | int |
You can change name of columns and table according to your wish.
Move old data accordingly.
Use query SELECT order_suborders.order_id FROM order, order_suborders WHERE order.id = ".$_GET['id']." AND order.id = order_suborders.parent_order
you can use explod to split with ","
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
//$array = array($sql_order);
$array=explod(",",$sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}

Mysql search with semi colon delimited string

I have 2 tables that look like this
table A table B
id | data id | features
--------- --------------
1 | blue 1A | 1;2
2 | red 2B | 1;2;3
3 | yellow 3B | 3;1
...... ......
What i plan to do is something like this, where i query one table. loop thru the array of results and explode the data with the semicolon delimiter. then loop thru that new array and query it to get the data (note code below not tested)
$sql = "SELECT * FROM `tableB` WHERE `id`= '2B' LIMIT 1";
$query = $db->query($sql);
while ($row = mysql_fetch_array($query)) {
$arr = explode(';', $row['features']);
for ($i = 0; $i < sizeof($arr); $i++)
{
$sql2 = "SELECT * FROM `tableA` WHERE `id`="'.$arr[$i].'"";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
}
}
print_r($r);
is there a way i can achieve this just in mysql, where i match the column in tableB with the ID's in tableA? or maybe by not using a nested loop? performance is key. coz both tables have more than 25k rows of data.
thanks in advance
Check out this code. Reduced few loops.
$sql = "SELECT * FROM `tableB` WHERE `id`= '2B' LIMIT 1";
$query = $db->query($sql);
$arr = explode(';', $row['features']);
$str = implode(",", $arr);
$sql2 = "SELECT * FROM `tableA WHERE id IN ({$str});";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
What you are looking for is the IN function
This will take an array of id's and give you every result in a single query.
So your code should look like this after you apply it
while ($row = mysql_fetch_array($query)) {
$new_query = str_replace(";", ",", $row['features']);
$sql2 = "SELECT * FROM `tableA` WHERE `id` IN ($new_query)";
$query2 = $db->query($sql2);
while ($row2 = mysql_fetch_array($query2)) {
$r[] = $row2['data'];
}
}

Categories