I have test table which is
this is my table i am comparing string and getting the entity_id from this table
my sql query for one value search is like this
Select entity_id From test Where BINARY value = '".$my_search_list."'
this works fine if i search for single value like Shirt
i want to search for multiple values and when i try it with Comma Separated value
like Root,Appare,hand Bags (more than work) it is not giving me output
i Also tried with this
Select entity_id From test Where BINARY value IN ( '".$my_search_list."' )
i don't want multiple query i want to do it in single query is it possible???
what i was thinking as i said is to create an array of keywords and see which one match the criteria then show all result.
$search = array('Root','Appare','hand Bags');
$sql = "SELECT `entity_id` FROM `test` WHERE ";
$count = 0;
$search_size = count($search);
foreach($search as $key)
{
$count++;
if($count < $search_size)
{
$sql .= "(`value` = '".$key."') or ";
}
else if ($count == $search_size)
{
$sql .= "(`value` = '".$key."')";
}
}
is you echo $sql you will see the correct query wich should work:
SELECT `entity_id` FROM `test` WHERE (`value` = 'Root') or (`value` = 'Appare') or (`value` = 'hand Bags')`
you need to use quotes for values
SELECT entity_id FROM test WHERE value IN ('one','two','three')
Related
code:
<?php
$this->db->select('*');
$this->db->from('bugs');
$where = "project_name = '".$project."'";
$this->db->where($where);
$sql = $this->db->get();
$res = $sql->num_rows();
if($res === 0)
{
$i = 1;
foreach ($bug as $row)
{
echo $i;
}
}
else
{
$i = 1;
foreach ($bug as $row)
{
echo ++$i;
}
}
?>
$data = array(
'project_name'=>$this->input->post('project'),
'bug_id'=>$this->input->post('bug_id'),
);
$query = $this->db->insert('bugs',$data);
In this code I have a table name bugs where I have a column i.e. bug_id. Now, I want to insert data into my table if table row having no value it insert bug_id = 1 and after that insert 2 and then 3 and so on. But now when I click on submit button it insert bug_id = 1 and then 2 but when I click on third it insert again bug_id 2 . So, How can I fix this problem?Please help me.
Thank You
MySQL has integrated AUTO_INCREMENT. Either you log into phpMyAdmin and change the properties of your bug_id field by clicking on edit, then selecting the "A_I" field.
Or you can do it with a SQL query:
ALTER TABLE YOUR_TABLE MODIFY bug_id INTEGER NOT NULL AUTO_INCREMENT;
If #Twinfriends answer doesn't fit your needs (but that should be the correct way to do that, you shouldn't reinvent the wheel) then maybe the problem is with your:
$data = array(
'project_name'=>$this->input->post('project'),
'bug_id'=>$this->input->post('bug_id'),
);
$query = $this->db->insert('bugs',$data);
Since you are actually using $this->input->post('bug_id') as your new id, maybe you want to use something else?
Where does your $bug var come from? To be sure of not getting duplicated ids or wrong one you could add to your MySql query something like "ORDER BY bug_id DESC LIMIT 1" (so that you take 1 row as result with the highest bug_id) and then just use that result + 1 as the new id
I need to check the array values which contains more than 400 values which is existing in the MySQL table where i should get result for all the values which I am passing even if it not exist in the column.
for example:
cont table
----------
Column1
---------
9xxxxxxxxx
91xxxxxxxx
92xxxxxxxx
my array contains 9xxxxxxxxx & 91xxxxxxxx. How can i iterate to get the column exist or not.
I tried with foreach and building query
$sql = 'SELECT cont WHERE num IN(';
foreach($jsonString as $val){
$sql = $sql . "'$val', ";
echo $val;
}
if(mysqli_query($con,$sql)){
echo "exist";
}else {
echo "error";
}
Is there any efficient way other than the above which is faster in time?
First of all if cont is your table name than where is FROM keyword.
If cont is column name than where is TABLE name?
As per your question, you have 400+ ids, than why are you using loop here? you can simply use implode() with comma seperated values, like
<?php
$ids = implode(",",$jsonString);
$sql = "SELECT * FROM cont WHERE num IN ($ids)"; // assuming cont is table name
?>
In your loop you will get the "," in last iteration at the end this will break your query.
I have a dynamic table in my db, that columns are altered and deleted from other scripts. Because there is a chance that all those extra columns might hold null or empty values eventually i want to have a 'cleanup' action somewhere that checks for those cells, and if all are empty, to drop the whole row.
The ones in red are the ones i want to check. If both columns are null or empty WHERE customers_id = 1, then DELETE row.
Like i said this is just an example...There could be 5 or 10 columns after customers_id. I need to check them all if they are empty.
I can get all the names of those extra columns in a string like this:
$temparray = array();
$q = mydb_query("SHOW COLUMNS FROM $table WHERE field NOT REGEXP 'id|customers_id'");
while($row = mydb_fetch_array($q)){
$temparray[] = $row['Field'];
}
$forSQL = " '".implode("', '", $temparray)."' "; // gives 'client_custom_contact_person', 'client_custom_password'
$forPHP = implode(", ", $temparray); //gives client_custom_contact_person, client_custom_password
What is the fastest way to check if all those column values are empty to drop that row ?
Should i go with a php foreach function ? Or is there a faster mysql query i could do ?
-Thanks
Figured it out. Using the $forPHP string:
$q2 = mydb_query("SELECT $forPHP FROM $table WHERE customers_id = 1");
$res = mydb_fetch_assoc($q2);
if(!array_filter($res)) {
//If all are empty then
mydb_query("DELETE FROM $table WHERE customers_id = 1");
}
I have to update the same value of multiple rows in a table and i would like to avoid multiple mysql_query using a foreach loop that scan every value of an array.
I try to explain using an example.
This is the solution of the problem using a foreach loop
$array=array(1,2,3);
foreach($array as $val){
$sql = "UPDATE mytable SET val_to_update = XX WHERE id = $val";
mysql_query($sql);
}
I didn't like to start hammering database with a crazy number of queries, because the number of element of the array is not fixed, and can also be large.
I have considered using the IN clause of SQL language but without knowing the number of parameters can not seem to find a solution.
Thinked at something like this, but I do not know if it is achievable:
$sql= "UPDATE Illustration SET polyptychID = $id_polyptych WHERE illustrationID IN (?,?,?);
and then bind all the parameters using a foreach loop for scan the array of parameters.
The problem, as I said, is that i don't know the number, so i can't place the right number of ? in sql query and, if I'm not mistaken, the number of occurrences of ? parameters must be the same as the binded parameters.
Anyone have solved a problem like this?
If you are sure, that the array is containing integers, why don't you do it like this:
$array=array(1,2,3);
if (sizeof($array) > 0 {
$sql = "UPDATE mytable SET val_to_update = XX WHERE id IN(".implode(',', $array).")";
mysql_query($sql);
}
If you want to use prepared statement you could create your sql using this code:
$array=array(1,2,3);
if (sizeof($array) > 0 {
$placeholders = array();
for($i=0; $i<sizeof($array); $i++) {
$placeholders[] = '?';
}
$sql = "UPDATE mytable SET val_to_update = XX WHERE id IN(".implode(',', $placeholders).")";
// .....
}
If the values in the $array exists in another table you could use something like this:
$sql = "UPDATE mytable SET val_to_update = XX WHERE id IN (SELECT id FROM another_table WHERE condition = 1)";
I want to execute a SELECT query but I don't how many columns to select.
Like:
select name, family from persons;
How can I know which columns to select?
"I am currently designing a site for the execute query by users.
So when the user executes this query, I won't know which columns selected.
But when I want to show the results and draw a table for the user I should know which columns selected."
For unknown query fields, you can just use this code.
It gives you every row fields name=>data. You can even change the key to '' to get ordered array columns by num following the columns' order in the database.
$data = array();
while($row = mysql_fetch_assoc($query))
{
foreach($row as $key => $value) {
$data[$row['id']][$key] = $value;
}
}
print_r($data);
First, understand exactly what data you want to retrieve. Then look at the database schema to find out which tables the database contains, and which columns the tables contain.
The following query returns a result set of every column of every table in the database:
SELECT table_name, column_name
FROM INFORMATION_SCHEMA.COLUMNS;
In this sqlfiddle, it returns the following result set (truncated here for brevity):
TABLE_NAME COLUMN_NAME
-----------------------
CHARACTER_SETS CHARACTER_SET_NAME
CHARACTER_SETS DEFAULT_COLLATE_NAME
CHARACTER_SETS DESCRIPTION
CHARACTER_SETS MAXLEN
COLLATIONS COLLATION_NAME
COLLATIONS CHARACTER_SET_NAME
COLLATIONS ID
COLLATIONS IS_DEFAULT
COLLATIONS IS_COMPILED
COLLATIONS SORTLEN
Now I know that I can select the column CHARACTER_SET_NAME from the table CHARACTER_SETS like this:
SELECT CHARACTER_SET_NAME
FROM CHARACTER_SETS;
Use mysqli::query to execute these queries.
If I understand what you are asking, you probably want to use MySQLIi and the the fetch_fields method on the result set:
http://us3.php.net/manual/en/mysqli-result.fetch-fields.php
See the examples on that page.
If you want to get column names for any query in all cases it's not so easy.
In case at least one row is returned you can get columns directly from this row.
But when you want to get column names when there is no result to display table/export to CSV, you need to use PDO functions that are not 100% reliable.
// sample query - it might contain joins etc.
$query = 'select person.name, person.family, user.id from persons LEFT JOIN users ON persons.id = user.person_id';
$statement = $pdo->query($query);
$data = $statement->fetchAll(PDO::FETCH_CLASS);
if (isset($data[0])) {
// there is at least one row - we can grab columns from it
$columns = array_keys((array)$data[0]);
}
else {
// there are no results - no need to use PDO functions
$nr = $statement->columnCount();
for ($i = 0; $i < $nr; ++$i) {
$columns[] = $statement->getColumnMeta($i)['name'];
}
}
Use mysql_query() and execute this query:
SHOW COLUMNS FROM table
Example:
<?php
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
}
?>
use DESC table or
Example
SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name='your_table';
output
column1,column2,column3
Use fetch_fields
$sql = "SELECT * FROM AT_EMPLOYEES;";
$result = mysqli_query($conn, $sql);
$finfo = $result->fetch_fields();
foreach ($finfo as $val) {
echo $val->name ."<br>";
}