Retrieving column name based on user input in MYSQL using php - php

Currently i am doing a PHP GET and getting values after clicking the submit button.
I got the values out from the submit button but I dont know how to reference them to the values in column.
For example, after clicking the submit button, I get the value 1.
Inside my database i have 3 columns
Col 1 Col 2 Col 3
2 3 1
How do i get the COLUMN name by just having the value itself? Thank you so much!

Ugly/silly, but would do what you want:
Query:
SELECT * FROM yourtable WHERE 1 in (col1, col2, col3, ... ,colN)
and then manually pick out the value in client code:
$row = mysql_fetch_assoc($result);
$matches = array_search(1, $row);
var_dump($matches);
You can't get away from listing all of the columns in the query, because there's no WHERE x IN (*)-type construct.

I would do it like this.
Get all table columns
then loop throug results and run select for each column
$columnVsValue = array();
foreach($columns as $column) {
$q = "SELECT id FROM table where {$column} = {$value}";
if(TRUE) { // you have to check that query return value
$columnVsValue[] = $column;
}
}
I did it quick probably there is more efficient way to do it

Related

How to create auto increment series number using mysql query?

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

MySQL return rows where column contains categories defined by array (and add weight to the results)

In my app, the user can type in an indefinite amount of categories to search by. Once the user hits submit, I am using AJAX to call my PHP script to query my DB and return the results that match what the user defined for the categories.
My category column is separated as so for each row: "blue,red,yellow,green" etc.
I have two questions:
How can I pass an array to MySQL (like so: [blue,yellow,green]) and then search for each term in the categories column? If at-least one category is found, it should return that row.
Can MySQL add weight to a row that has more of the categories that the user typed in, therefor putting it further to the top of the returned results? If MySQL cannot do this, what would be the best way to do this with PHP?
Thanks for taking the time and looking at my issue.
For the part 1 you can use the function below:
<?php
function createquery($dataarray){
$query="select * from table where ";
$loop=1;
foreach($dataarray as $data)
{
$query.="col='$data'";
if(count($dataarray)<$loop-1){
$query.=' or ';
}
$loop++;
}
return $query;
}
?>
This will return the long query.
use this some like this:
mysql_query("select * from table where category in (".implode($yourarray,',').")");
1)
Arrays are not passed to a MySQL database. What's past is a query which is a string that tells the database what action you want to preform. An example would be: SELECT * FROM myTable WHERE id = 1.
Since you are trying to use the values inside your array to search in the database, you could preform a foreach loop to create a valid SQL command with all those columns in PHP, and then send that command / query to the database. For example:
$array = array('blue', 'red', 'yellow', 'green');
$sql = "SELECT ";
foreach ($array as $value)
{
$sql .= $value.", ";
}
$sql .= " FROM myTable WHERE id = 1";
IMPORTANT! It is highly recommended to used prepared statements and binding your parameters in order not to get hacked with sql injection!
2)
You are able to order the results you obtained in whichever way you like. An example of ordering your results would be as follows:
SELECT * FROM myTable WHERE SALARY > 2000 ORDER BY column1, column2 DESC

Update mySQL table if row from another table is certain value

UPDATE table1 SET row1 =CONCAT( row1, 'word1, word2')
I want to add a condition to the query above.
I'm looking to add text values to row1 on table1, which already contains some texts, the query above does the trick, but additionally to that, I need to add a condition. I have another table called "table2", with a column, let's say "row2" that equals to "1". I need to run the query above IF row2 in table2 equals to 1.
I'm running the query directly on PHP MyAdmin
Thanks in advance.
$query = "SELECT `row2` FROM `table2`";
$res = mysqli_query($query);
$row = mysqli_fetch_array($res);
if($row['row2'] == 1)
{
//run your update table code: UPDATE table1 SET row1 =CONCAT( row1, 'word1, word2')
}

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 fetch column value of particular row

I need to fetch a particular column value of a particular row using php in mysql.
For example if I want to fetch column2 value in row2, I tried using:
$qry = mysql_query("SELECT * from $table");
$data = mysql_fetch_row($qry);
$result = $data[1];
but this always returns only the first row value.
SELECT Column2
FROM $table
ORDER BY Something
LIMIT 1,1;
Or, if you know the key of the row
SELECT Column2
FROM $table
WHERE Key = Something
-- Optional: if you want 2nd after filtering
-- ORDER BY Something
-- LIMIT 1,1;
select COLUMNNAME from TABLENAME where ROWELEMENT="SOME_VALUE";
This should be your sql query..
You will need to access the value of that element using
$result['COLUMNNAME']
Complete code should look like this.
$query="select COLUMNNAME from TABLENAME where ROWELEMENT='SOME_VALUE'";
$result=mysql_query($query);
$result=mysql_fetch_array($result);
$columnvalue=$result['COLUMNNAME'];
Its bcoz mysql_query returns the result in an associative array form.
After the above code, You can access all elements like this.
$columnname[$index];
This will return the first value,
According to your question, You will need to first get the column values in a saperate array, and then access it using your index value..

Categories