Need help writing an array_diff() query for mysql - php

I'm using PHP but that's not important. I have a variable that contains a standard array of positive int IDs. And I want to do a SELECT query with this array against a MySQL table to find out what IDs are not already existing in the data table. My first thought was to use IN() but then I realized that doing it that way I can only get a list of IDs that do exist not ones that don't. Of course with a list of IDs that do exist, I could compile it into a second array and then use array_diff() but I can't help wondering if there's another way to do it.

I decided to use unset()
SELECT QUERY
where (row) {
unset(id)
}

Related

Laravel 4 Query groupBy: all columns from table

I have to call the $model->groupBy(?allcols?) function with all columns as a param.
How should I do this?
Edit: I have all Columns as an Array, so i can't pass them like 'col1','col2',...
I'm asking this because i have this poblem (github) and i found out, that there the prob is on Line 119.
I tried it manually like col1,col2 which worked, but it should by dynamically for all models.
I found this snippet, to get all cols from the current table as an array, but i can only pass a String.
Ok, if I'm understanding your edit correctly, you've got an array of column names you wish to group by. If $model is the name of your query, I'd recommend just using a foreach loop and appending each field:
foreach($allcols as $col){
$model->groupBy($col);
}
$model->get();
There is no such function for grouping all columns but you may use groupBy(col1, col2, ...), for example, if you have a posts table then you may use:
DB::table('posts')->groupBy('col1', 'col2')->get();
Or using Eloquent Model, for example a Post model:
Post::groupBy('col1', 'col2')->get();
If all you're trying to do is get rid of duplicate records (which is all that groupBy(all) would do as far as I can envision), you could also just use $model->distinct() instead. However, unless you add a select() to exclude the id field, you're going to wind up with the full recordset with no grouping, as by definition the id is unique to each record and thus won't collapse across records by either manner.

Reducing multidimensional array to linear

I have asked a question similar to this, but none answered. Im guessing because it was too long that i wasnt able to fully state or make it clear to the general public. Anyways, Is there anyway into reducing an array like this
Array( [0]=>Array( [id]=>name ) [1]=>Array( [id]=>name ) )
The above values came from.
$query=$this->db
->select('id,name')
->from('employees')
->get()
->result_array();
The query above results,
Array([0]=>Array([id]=>1 [name]=>john))
Since i wanted to get all the rows without overwriting the previous rows resulted. I added this algo.
foreach($query as $row)
{
$employee_list[] = array($row['id']=>$row['name']);
}
Now the results are not overwritten so if i print_r($employee_list);
I would echo out, assume there are 2 rows in my employees table.
1-john,2-peter
Array([1]=>Array([1]=>john) [2]=>Array([2]=>peter))
My question now is, how do i reduce the above resulted array to one dimensional/linear. Since the ID is stored as KEY and the id column is INTEGER AUTO INCREMENT PRIMARY KEY so it doesnt have any duplicates which means for every row inserted the id will be incremented.
so it would be fine if the array i wanted would be.
Array([1]=>john [2]=>peter)
Additional INFO: I am using codeigniter as my framework, so if there's any defined function in the CI library, it would help if anyone could tell me if there is any.
In old times you could use mysql_result which selects one column into single dimensional array.
However, it is deprecated since PHP 5.5.0 and the reference suggests using mysqli_fetch_field (which forces you to make a select from the response as zerkms suggest in the comment) or PDOStatement::fetchColumn if you are willing to use PDO.

Loop in query function without "while"

Is it possible to show all rows with the properties from my query using only different last function. Something different from fetch_object();?
here is my query:
$dbo_training = $db->query("select * from tabela where id='$tr'")->fetch_object();
which is showing me only one row...
Not sure i completley understand you but if what you want is an array of all the results, the method fetch_object() only returns the first row by definition. try using fetch_assoc() to get an array containing all the results.
I guess you are using mysqli::fetch_object(). If so, you might want to have a look at mysqli::fetch_all which »Fetches all result rows as an associative array, a numeric array, or both« (but apparently not as array of objects…) If you need the objects, you'll probably have to stick to a while loop. (And there is nothing bad about a while loop per se)
I don't know what ORM you are using but with PDO (the PHP standard database accessor) you have to call fetchAll() to do that. If you are using your own library you should have a look to PDO which is very powerful!

How do i store a field from a MySQL database as a string in PHP?

One of my fields in my data base is an array which has been converted to a string using the implode() function.
How do I retrieve the contents of this field (LESSONS) from the database and store it to a string when a user entered value is equal to the the value of the field NAME?
Thanks in advance for any help you may be able to provide.
Here you go:
$r = mysql_query('SELECT LESSONS FROM TABLE WHERE NAME=\'user_string\'');
$rows = mysql_fetch_assoc($r);
echo $rows['LESSONS'];
I don't know if I understood your question but... Take a look about Stored Procedures
If you used the implode function to convert your array into a string, then this data has lost any information about the array keys.
As far as you want to convert the data back, use the explode function:
$array = explode(',', $columnData);
But You can therefore not search for array keys within the database.
Next to that, the MySQL database (I assume you're using MySQL) can not search for array keys anyway.
You need to store the data in some other way into the mysql to search for it in an SQL later on.
For example, you can create a table that stores key/value combinations with a grouping index.
However MySQL has some string functions that can help you searching within the (now) string data in the MySQL database.
When searching for a value, before the comparison add a comma at the beginning and one at the end of the string. There is a MySQL string function that can concatenate strings. Then search within that expression for your value with a comma added in front and back as well.
Then you can lookop a single array element within the mysql database. MySQL String Functions.
This is a quick solution only, this won't work on large databases performant. However it might solve your problem w/o changing your database structure.

reorder results of mysql query php

I run a mysql query that gets specific results from a table. I then want to print these results in two html tables. The first ordered by one column which is already done by putting ORDER BY into mysql query. But then I want to print the results ordered by a different column. However, I don't want to run a mysql query again as this is too slow.
So to sum up:
Is there a way to reorder the results of a mysql query?
(sorry if the question is unclear, it is my first time using the site.)
PHP has some really great sorting functions. I would most likely make a user-defined sorting function and use that with your result set:
http://php.net/manual/en/function.usort.php
Sorting with PHP is generally very fast. Faster than a 2nd query if your result set is not too large.
You can simply reorder the resultset yourself with one of the sorting methods in php.
http://php.net/manual/en/array.sorting.php
I assume you would want to use usort() here: http://php.net/manual/en/function.usort.php
Why not show it just once and use the jQuery Table sort plugin. Also, if you want to show it twice, there is no problem in making the table sortable.
The advantage would be performance increases as you are transferring the sort operation from server side (PHP) to client side (Javascript).
If you really want to use the sorting features in MySQL, as opposed to those in PHP, one option is to write your PHP code to query twice. In your first query:
SELECT id FROM table_name WHERE (whatever) ORDER BY first_criteria
Then in the second query, fetch rows:
WHERE id IN (2,17,388,etc.)
ORDER BY different_column
. . . passing the IDs from your first query into the IN clause, of course.
Not sure whether this would be faster or slower than sorting in PHP. Might be worth testing.

Categories