I have this mysql table.
name | total
chris | 5
jan | 3
bob | 2
eric | 4
chris and jan were selected using this code
$query = " select * from table where name = '$given_name' ";
// &given_name = result from another query
I want to store the result of the query to a variable.
while($row=mysql_fetch_assoc($query)){
$result = $row['name'];
} // i want to store both chris and jan to $result
Then i will use the result of the query to another query. I want to select the remaining names. Not the ones on the first query. I want chris and jan not to be selected with this query because it is stored in $result
select * from table where name != $result ;
But one name was just stored in $result. I want them both to be stored in $result.
You could use FIND_IN_SET to see if the names had been fetched before. Firstly you need to make $result an array of all the names:
$result = array();
while ($row=mysql_fetch_assoc($query)) {
$result[] = $row['name'];
}
Then you can write your query to exclude the names in $result:
$sql = "SELECT * FROM table WHERE NOT FIND_IN_SET(name, '" . implode(',', $result) . "')";
You can use database query like below to exclude chris and jan:
select * from table where name NOT IN( $result );
Assuming that you do not know the names of the resultset you can simply (a) select the first two names from the resultset, (b) concatenate them in a string and finally (c) use "NOT IN" as your query parameter.
$numPicks = 2; // decide how many names you want in the list
// OR if you want to exclude ALL names found in the first query
$num_rows = mysql_num_rows($query);
$nameList = ''; // start with an empty string
for($i=0; $i<$numPicks; $i++) { // then use $num_rows here instead of numPicks
$nameList .= $row['name'].',';
}
$nameList = rtrim($nameList,','); // remove trailing comma from the string
$sql = "select * from table where name NOT IN ($nameList)";
Related
I have a MySQL table that looks like this
index (auto incremented)
data
type
1
a1
1
3
a2
1
4
b62
3
9
m52
1
and i loop through it with this code
for($i=1; $i<= number of rows; $i++){
$query = "SELECT * FROM messagesforinstructor where type='1' and index='$i'";
$result = mysqli_query($db, $query);
$display=mysqli_fetch_assoc($result);
echo $display['data'];
}
but as you can see that it would fail cause the auto incremented indexes are not sequential.so at i=2 it would fail without making it to i=3.
any idea how to make it select the next index in the table
Simple solution
Don't use * use specified column names
Use one query to retrieve the entire result set
Use OOP approach and save yourself having to repeat code (you don't neeed to change the connection but you can:
// From...
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
// To...
$db = new mysqli($db_host,$db_user,$db_pass,$db_name)
I assume that type is an integer field; no need to use quotation marks in the query
Code
// Run the query to select the messages
$sql = "SELECT data FROM messagesforinstructor WHERE type = 1";
$query = $db->query($sql);
// Option 1
// Loop though result set with a foreach loop
foreach ($query as $message) {
echo $message[0];
}
// Option 2
// Loop through the result set with a while loop
while ($message = $query->fetch_assoc()) {
echo $message["data"];
}
I have some comma-separated records that I am saving in a MySQL database.
I have the following table and records:
tbl_checks
id | items
----+------
1 | 2,5
2 | 2,3
So I would like to fetch data where one of the comma-separated values in the column items is 5.
I have tried:
$sql = "SELECT * FROM tbl_checks WHERE items="; //unable todo at here
so that I can:
$results = $this->db->query($sql)->result() //codeigniter script
I have also tried
$sql = "SELECT * FROM tbl_checks WHERE items=".in_array(5)//this fails
Your current approach isn't that good, if you want to query against this field. Normally, you would use normalization and split that data into multiple tables which could queried better.
If you have stuck with this approach, you could use LIKE and CONCAT.
$id = '2';
$sql = "SELECT * FROM tbl_checks WHERE CONCAT(',', items, ',') LIKE '%,$id,%'";
$value = 5;
$result = $this->db->where("FIND_IN_SET($value,items) !=", 0)
->get("tbl_checks")->result_array();
I'm agree that such database isn't good constructed. Any way this query should work:
SELECT *
FROM tbl_checks
WHERE ( items LIKE "5,%" )
OR (item LIKE "%,5");
The query SELECT * FROM TABLE WHERE id LIKE '%1% is not working properly, it's not select the id 1.
mysql_connect('localhost', 'root' , '');
mysql_select_db('database');
$sql = ("select * from search WHERE id LIKE '%3%'");
mysql_query($sql);
$my_variable = mysql_query($sql);
$display_data = mysql_fetch_row($my_variable);
while ($list = mysql_fetch_assoc($my_variable)) {
$id = $list['id'];
$title = $list['title'];
$keywords = $list['keywords'];
$img = $list['img'];
$link = $list['link'];
}
If you are looking to SELECT id 1 then use = not LIKE. The way LIKE is being used it will match every id that has a 1 in it and you are not guaranteed to get the first one in order, so instead use:
SELECT * FROM search WHERE id = 1
According to the PHP documentation of mysql_fetch_row it
Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.
Which means that the first result won't show up in the next (mysql_fetch_assoc) procedure. You could try removing the $display_data = mysql_fetch_row($my_variable); line and only use the while($list = mysql_fetch_assoc($my_variable)) { ... } procedure. See if that solves your problem.
$sql = ("select * from search WHERE id ='3'");
The id is an integer use = instead of like . Equal is more accurate.
And first echo your query in your program->
echo $sql;die;
copy that query and run it on your phpmyadmin
and then check is your column id is int type if it is then like will not give you the result. You have to use the where clause here .But if you have the column id is of type varchar then definitely give you the result .
Try to use search tab under your database->table in your phpmyadmin and put the condition there.
You will definitely get your answer there.
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];
}
}
I have a database that stores the users name, number, and carrier in a table called user.
I need to know how to write a query that if my value is equal to name - it will fetch the number and carrier associated with that name. I am writing this in php and will use javascript if necessary.
I should prefer you to use "SELECT * FROM user WHERE name LIKE '{$value}'"
because using = will search for the exact value
For example: if in database the value is john and u searched for John it will not display the result but if you use LIKE it will display all the related results like JOHN, john, John, jOHN etc.
Thanking You,
Megha
You can just put one of the following:
1)
$value = "John";
$result = mysql_query( "SELECT * FROM user WHERE name LIKE '$value'" );
above query will return rows matching name like JOHN, john, John,etc as suggested by Megha.
2)
$value = "John";
$result = mysql_query( "SELECT * FROM user WHERE name='$value'" );
above query will return rows matching name with the value 'John'.
Your SQL query will look like this:
"SELECT * FROM user WHERE name = '{$value}'"
This selects all columns in the table user where the name column has a value of the PHP variable $value
You can execute this query using PHP's MySQL functions: http://php.net/manual/en/book.mysql.php
Example
$value = "John";
$result = mysql_query( "SELECT * FROM user WHERE name = '{$value}'" );
while( $row = mysql_fetch_array( $result ) )
print( "Column with name columnName has a value of " . $row['columnName'] );