One query for every number in row - php

If I have a database with a field called items with '1,2,3,7,15,25,64,346' in it.
Is there a function to use the commas as a separator and take each number and start a new query and get info for that id? Like a foreach but in sql?
I can see it so clear but cannot put it in words...

You can use this query,
SELECT * FROM TABLE_NAME WHERE COLUMN_NAME in (1,2,3,7,15,25,64,346);

Yes, there is. You can use command IN
mysql_query( 'SELECT * FROM `table` WHERE `id` IN ( 1,2,3,4,5 );' );
WHERE - IN

$row = '1,2,3,7,15,25,64,346'; // $row = $field['value']
$arr = explode(',',$row);
foreach($arr as $a) {
// write your query
}

You can use the query SELECT * FROM table_name WHERE id IN ( 1,2,3,4,5 ) to find data having id's.
No need to separate the values. This will give you the desired result.

There is so way to do a "SQL foreach". Do it using PhP
Also, having such fields means your database is not normalized. You should give a look at relational database normalization, otherwise the bigger your database will be, the bigger your problems will be.

It seems you want data like this where 'source' is table having the column
SELECT target.* FROM target
LEFT JOIN source ON FIND_IN_SET(target.id, source.ids_row)

Related

Select all cells that are not empty MYSQL

I have a table where I need to find wheter the cell is empty or not.
I don't have the specific column name so I need to display all of the cells that are not empty. (PHP solution would fit too.) Thank you!
Here is my piece of code:
$result1 = mysql_query("SELECT * FROM `FACILITIES` WHERE `room_id` = '{$row['id']}'");
while($row1 = mysql_fetch_assoc($result1)) {
if(empty($row[''])) { //What should I fill in in the $row variable?
alert("Empty");
}
}
I have tried doing in in PHP, but a MYSQL solution would fit too.
You should prevent that problem in the first place. Handle that on DB design level. If you want all your records having values in every column, then define the columns so: not null.
a simple sql that you can rewrite and use would be similar...
sqlfiddle
select * from t where
(col1 is null or col1='')
or
(col2 is null or col2='')
;
sqlfiddle

MYSQL Statement with Array Variable

So I have the following mysql statement saving to an array:
$sql = "SELECT did FROM did WHERE id = '$did_id'";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
while($row = $result->fetch_row()){
$did[] = $row;
}
That part works great. But now I need to take the values in the $did array and perform another lookup using the values in it. The way it works is we have users assigned to certain did's. So I find the did's that the user is assigned to (the $did array) and only show them results from another table based on those did values. I have no idea how this part works, but this is what my next statement needs to do:
SELECT * FROM log WHERE did_id = "the values in $did array"
Hope someone can help. I really appreciate it. I haven't really been able to find anything on it.
You can use php's join with mysql's IN to make comma separated strings you can also use implode , join() is an alias of implode();
SELECT * FROM log WHERE did_id IN( ".join(',',$did).")
One thing to mention here that your $did should contains ids in manner like
array("1","2","3"....)
So in your loop fetch first index that holds did column value
$did[] = $row[0];
Note: i assume did , did_id type is int or bigint

PHP: How do I select from MySQL table by column position rather than by column name?

I have a table that has multiple columns, the column names can be changed in the future, and rather than my script select from the columns by their name (since that info can change), is there a way to select by column position?
For example, I want to select the second column in the table... can I do that easily?
I understand the reasons not to do this, but I still want to.
Easy solution? Just SELECT * FROM table, fetch with $row = mysql_fetch_row() and read from $row[1], it will be the content of the "second column" in order (as it starts in 0).
If you want it a little bit more professional and select only whats needed, you can get the second column name from the INFORMATION_SCHEMA using a query like this:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'your database schema' AND TABLE_NAME = 'the wanted table name' AND ORDINAL_POSITION = 2;
But if you really want to do this the right way then know where you put your nose. If the table structure is changed and your code needs adaptations because of it, so be it. This is how it should be done. If you leave it "working" but relying in potentially wrong information it may cause much bigger problems to you later.
This is such a bad idea that I almost don't want to give you a solution, but it is possible. MySQL has a database named information_schema that stores DDL data that you can query. What you are after would be COLUMNS.ORDINAL_POSITION.
SELECT COLUMN_NAME FROM information_schema.COLUMNS
WHERE TABLE_NAME = ? AND ORDINAL_POSITION = ?
This will give you the name of the nth column, which you can use in the field list of a subsequent query. It would not make sense to do this in a single query.
The following three exampels shows you how to print the 3rd column using MySQL, MySQLi and PDO.
MySQL
while ($row = mysql_fetch_array($query)) {
print $row[2];
}
MySQLi
$sth->execute();
$sth->bind_result($var1, $var2, $var3);
while ($sth->fetch()) {
print $var3;
}
PDO
$sth->execute();
while ($row = $sth->fetchAll()) {
print $row[2];
}
In PHP you can execute query using $res = mysql_fetch_row($query). then you can fetch second column by $res[1];
I have had such problem many days ago. But I found the solution:
$conn = new mysqli("localhost", "root", "", "Mybase");
$result = $conn->query("SELECT * FROM imagesbase");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_BOTH)) {`
$outp .= "Picture: ".$rs[0]." ".$rs["ImgPathName"]."";`
}
$conn->close();
echo "$outp";
This code may be changed by column number or column name. MYSQLI_BOTH , MYSQLI_NUM or MYSQLI_ASSOC are used for this.

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

MySQL row selection

I have a table as below,
ID Name Age
----------------------
100 A 10
203 B 20
Now how do i select only row1 using MySQL SELECT command and then I've to increase +1 to it to select row2. In short I'll be using for loop to do certain operations.
Thanks.
Sounds like you've got a mix up. You want to select all the rows you want to iterate through in your for loop with your query, and then iterate through them one by one using php's mysql functions like mysql_fetch_row
You should not try to use tables in a linear fashion like this. Set your criteria, sorting as appropriate, and then to select the next row use your existing criteria and limit it to one row.
SELECT * FROM `table` ORDER BY `ID` LIMIT 1
SELECT * FROM `table` ORDER BY `ID` WHERE ID > 100 LIMIT 1
You'd probably be better off retrieving all rows that you need, then using this. Note the LIMIT is entirely optional.
$query = mysql_query(' SELECT ID, Name, Age FROM table_name WHERE condition LIMIT max_number_you_want '))
while ($row = mysql_fetch_assoc($query)
{
// Do stuff
// $row['ID'], $row['Name'], $row['Age']
}
Lots of small queries to the database will execute much slower than one decent-sized one.
You should get the result into an array (php.net : mysql_fetch_*).
And after you'll can loop on the array "to do certain operations"
Yep, this is a pretty common thing to do in PHP. Like the others who have posted, here is my version (using objects instead of arrays):
$result = mysql_query("SELECT * FROM table_name");
while ($row = mysql_fetch_object($result)) {
// Results are now in the $row variable.
// ex: $row->ID, $row->Name, $row->Age
}

Categories