single sql database entry with muliple values into an array - php

the script querys database and retrieves a single entry that has mulitple numbers
SELECT jnum from database where x = y
output = 11111,22222,33333,44444
So i explode that on , and get $variable[0] = 11111 and $variable[1]= 22222
What i want to do is perform a query on another table using each of those numbers (numbers will be different each time and there may be any number of numbers).
is there a way to structure a foreach for each entry in the array or a while loop that counts so that i can query the database for each of the values i get from output above.
i don't know if i am conveying what 'im trying to do here very clearly so i apologize in advance.
i get a single entry for the database table and it contains a string (11111,22222,33333)
i explode on , and get the array variable[]
there will not always be 3 entries sometime there could be 5 or 7 or 10 or 1 but each one will be unique.
but for each value i want to query a db table and retrieve all the rows that have that single number($variable[]) as an entry.
Not sure if a loop count or a foreach statement would work. any ideas?

Well assuming these are values in a single column there is no need to look you can use WHERE ... IN:
SELECT * FROM the_other_table WHERE some_col IN ('11111','22222','33333')

Check out foreach loops - http://php.net/manual/en/control-structures.foreach.php
foreach ($variable as $value) {
$myquery = "some query using $value";
// then execute your query
}

Related

Get row numbers from mysql_fetch_array result

I have pulled in the data from a mysql database using select * with the intention of using the data several times without doing repeated sql enquiries using WHERE.
Using this data I am extracting rows that contain a search element using
while($row=mysql_fetch_array($query_result)){ <<<if match add to new array>>> }
As there are thousands of rows this is taking a longer time than I want.
I am trying to use:
$row=mysql_fetch_array($query_result);
$a = array_search($word_to_check, $row);
echo $a;
This extracts the correct sql headings but not the row number. What I want to achieve is
if $word is found in mysql_fetch_array($query_result) the add the row where it was found into the new array for processing.
Any thoughts? Thanks in advance.
Don't use mysql_* functions they are depracated. Use mysqli or pdo instead.
It's not wise to search in array of mysql results in php while it can be done in mysql. Let's say you have table and you want to find all numbers in number column that are greater than 5
SELECT FROM table_name WHERE number>5
to find text you can use simple clause
SELECT FROM table_name WHERE name = 'username'
You can also create more complex conditions.
From MYSQL manual:
WHERE clause, if given, indicates the condition or conditions that rows must satisfy to be selected. where_condition is an expression that evaluates to true for each row to be selected. The statement selects all rows if there is no WHERE clause
Check this link
If you want to limit the query to only once, fetch all the results into temporary array and do the search from it like below
<?php
$all_rows=array();
$match_rows=array();
$i=0;
$limit=100000;
while($row=mysql_fetch_array($query_result)){
$all_rows[]=$row;
if($i % $limit == 0){ // this part only functions every 100,000 cycles.
foreach($all_rows as $search_row){
if(array_search($word_to_check, $search_row)
$match_rows[]=$search_row;
}
$all_rows=array();//reset temporary array
}
$i++;
}
//This solution assumes the required word can be found in mulitple columns

mysql In clause to avoid loop

I have to retrieve the history of a user and I have 4 tables whose data depend on each other.I can retrieve the data using loops,but I instead used the "where IN ()" clause and I implode the output of the previous query.However,if the list I provide to "where IN()" is empty it return an error.Is it that IN() cannot be empty?
When imploding an array for the IN clause, i do one of two things
1: Check if you even need to run the query at all
if(!empty($some_array)) {
//run mysql query
}
else {
// if you need to do something if the array is empty, such as error or set some defaults, do it here
}
2: A value in the array initiliser which is not ever in the database (for example, if im selecting based on a auto incrememnt id, i use zero as a default array value to stop any issues with empty data sets, as zero will never be in my id column).
$some_array = array(0);
You can add an empty value to the start, such as IN (0,your values here)

INSERT: inserting multiple rows at once, or one by one?

I'm inserting multiple rows in a table, and I get this message:
MySQL server has gone away
My Query:
INSERT INTO table
(a,b,c,d,e,f,g,h,i,j,k)
VALUES(1,2,3,4,5,6,7,8,9,10,11),(1,2,3,4,5,6,7,8,9,10,11), ...
ON DUPLICATE KEY UPDATE
c=VALUES(c),
d=VALUES(d),
e=VALUES(e),
f=VALUES(f),
g=VALUES(g),
h=VALUES(h),
i=VALUES(i),
j=VALUES(j)
Is it because I stuffed too many values inside a single query? (There are like 5000 pairs of values from a array which I implode with ,).
If this is the reason - then should I insert each row one by one? Is it slower than inserting them all at once?
The PHP code:
foreach($data as &$entry)
$entry = "('".implode("','", array(
$entry->ID,
addslashes($entry->field_1),
addslashes($entry->field_2),
...
))."')";
$data = implode(',', $data);
$query = "... VALUES{$data} ON ..."
$data is a array of STD type objects...
edit again :)
So I tried splitting my $data into smaller arrays of 100 elements each:
$data_chunks = array_chunk($data, 100);
foreach($data_chunks as $data_chunk)
insert_into_db($data_chunk);
and it works, I don't get that error anymore...
So that means the issue was the very long query string...
Now I'm even more confused:
Is there a length limit of the query, or maybe PHP arguments in general?
Is there any difference between inserting row by row than inserting multiple rows? Is it worth the array_chunk() ?
it could be that your query is taking too long to complete, mysql times out and closes the connection. You can alter the system variables to wait longer.
http://dev.mysql.com/doc/refman/5.0/en/gone-away.html
I think your problem is with *max_allowed_packet*, although the error seems to point in different direction. Try doing as suggested here: http://dev.mysql.com/doc/refman/5.5/en/packet-too-large.html
Or, before making any changes to mysql configuration, simply strlen() your query and find out how long(in bytes) it actually is.

SQL - Inserting multiple row values into a single column

I need help on a method of inserting values into a single column on different rows.
Right now, I have an imploded array that gives me a value such as this:
('12', '13', '14')
Those numbers are the new IDs of which I wish to insert into the DB.
The code I used to implode the array is this:
$combi = "('".implode("', '",$box)."')"; // Where $box is the initial array
The query of which I plan to use gets stuck here:
mysql_query("INSERT INTO studentcoursedetails (studentID) VALUES
One option would be to repeat this, but I cant, because the array will loop; there might be 3 IDs, there might be 20.
A loop doesn't seem right. Any help would be appreciated.
For inserting more than one value into a table you should use (value1), (value2) syntax:
$combi = "('".implode("'), ('",$box)."')";
PS: This feature is called row value constructors and is available since SQL-92
Can you not do something like this:
for($x = 0; $x < count($box); $x++)
{
mysql_query("INSERT INTO studentcoursedetails (studentID) VALUES ($box[$x]);
}
This will work directly on your array, insert a new row for each value in $box and also prevent the need to implode the array to a comma delimited string
Storing ids as a comma delimited string might initially seem like a simple model but in the long term this will cause you no end of trouble when trying to work with a non-normalised database.
Some flavors of sql allow compound inserts:
insert into studentcoursedetails (studentid) values
(1),
(2),
(3),
If you are using MySQL, you can insert multiple values in a single sentence:
sql> insert into studentcoursedetails (studentID)
> values (('12'), ('13'), ('14'));
So, you just need to build that string in PHP and you are done.
You can still create the statement via implode. Just don't use VALUES; use SELECT instead
$combi = " ".implode(" UNION ALL SELECT ",$box)." "; // Where $box is the initial array
mysql_query("INSERT INTO studentcoursedetails (studentID) SELECT " . $combi)
The SELECT .. union is portable across many dbms.
Note on the IDs - if they are numbers, don't quote them.
Check to see if there is a variant of the mysql_query function that will operate on an array parameter.

How do I get distinct values from an array stored in MySQL?

I have a MySQL field which stores an array with 3 values:
array(item1=>1123, item2=>5454, item3=>23432)
How can I query the database with PHP so that I get only distinct values of item2 and then arrange those results by the values of item3?
A lot more information is needed - like, how your database is structured.
Look into the DISTINCT() function and the ORDER BY clause of SQL
It much easier to store your array into text and something you can separate later. Using php you can do this. I'll try to work with your data here into something you can use. says you have the field items. If instead you had an array such as.
$items = array(1123,5454,23432);
You can then implode it with a symbol such as:
$items = implode('|',$items);
and then store this in the database under a fields such as items that would look like this:
1123|5454|23432
Then when you want to grab the data you just need to explode it with the same symbol:
$items = explode('|',$row['items']);
and you are back with your dataset:
$items[0] = 1123
$items[1] = 5454
$items[2] = 23432
and then can access the second item by grabbing element one of the array:
$items[1]
Hopefully that gives you a better understanding of it.

Categories