Querying MySQL table using dynamic variables - php

I am trying to Query a MySQL table to to bring any result that matches data that the user has input. The database,table and column names are also dynamically stored in variables. var_dump produces a bool(false) which means my query is wrong.
My Code
if (isset ( $_POST ['name'] )) {
$name = trim ( $_POST ['name'] );
$tblName = $_REQUEST ['tbl'];
$colqry = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$dbName' AND TABLE_NAME = '$tblName'";
echo "<ul>";
$col_names = mysqli_query ( $link, $colqry );
while ( $col = mysqli_fetch_array ( $col_names, MYSQL_ASSOC ) ) {
$colName = $col ['COLUMN_NAME'];
$tblQry = "SELECT * FROM $tblName WHERE $colName=$name LIMIT 10";
$query2 = mysqli_query ($link, $tblQry);
echo $query2;
while ( $query3 = mysqli_fetch_array ( $query2 ) ) {
echo "<li onclick=fill'" . $query3 [0] . "'>" . $query3 [0] . "</li>";
}
}
}
What I want to achieve is list a table where the search terms matches something on the table either the column name or the data inside the columns

This line:
$tblQry = "SELECT * FROM $tblName WHERE $colName=$name LIMIT 10";
Quote the $name variable:
so it reads as WHERE $colName='$name'
You can then use $query3[$colname] to get the search match you're looking for.
For more information on identifer qualifiers, visit:
http://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html

Related

How to SELECT a JSON column in MySQL and return as an Array()

I have a JSON column (called json_col) in a MySQL table:
{'a':9, 'b':8, 'c':7}
I want to select the column "json_col" with each of its keys and values and return it as an array() so I can process it in PHP.
How do I do that?
I tried JSON_EXTRACT() but that requires me to specify the json element and it only returns the corresponding value.
Here is "my effort":
$query_string = '
SELECT JSON_EXTRACT( json_col, "$.a" )
FROM settings
WHERE id = "4"
LIMIT 1
';
$result = mysqli_query( $GLOBALS['db_link'], $query_string ) or die( mysqli_error( $GLOBALS['db_link'] ) );
$row = mysqli_fetch_row( $result );
mysqli_free_result( $result );
When I echo $row[0] I get the value of "a" which is 9!
Simply Change your query to select the json:
$query_string = '
SELECT json_col
FROM settings
WHERE id = "4"
LIMIT 1
';
Execute your query as you did before
$result = mysqli_query( $GLOBALS['db_link'], $query_string ) or die( mysqli_error( $GLOBALS['db_link'] ) );
$row = mysqli_fetch_row( $result );
And then convert it to an array with json_decode
$myArray = json_decode($row['json_col'], true);
You can check its values like this:
echo "<pre>";
print_r($myArray);
echo "</pre>";

how to select primary index of a table as a column in select command

I have a table , Here is my table image
my Query Select * from categories My question is how i can fetch or echo primary index of my table after executing above query.
<?php echo "Primary field is =".$rec['primary_field_name']; ?>
And the output from same query is as
Primary field is = cat_id
Thanks in advance
I think this should do what you want:
<?php
$conn = mysql_connect( $dbhost, $dbuser, $dbpass );
mysql_select_db( $dbname );
$sql='select * from `categories`;';
$res=mysql_query( $sql, $conn );
if( $res ){
while( $rs = mysql_fetch_object( $res ) ){
echo $rs->cat_id . ' ' . $rs->cat_desc .' '. $rs->cat_status.' '.$rs->cat_image.'<br />';
}
}
mysql_free_result( $res );
mysql_close( $conn );
?>
As I misunderstood your question the following query MIGHT be of interest to you.
select `column_name`
from `information_schema`.`columns`
where (`table_schema` = database() )
and (`table_name` = 'categories')
and (`column_key` = 'pri');
Though I don't know of a way to get the name of the primary key within a standard sql query.
You could try the following as an "All in One" solution:
select *,
( select group_concat(`column_name`)
from `information_schema`.`columns`
where (`table_schema` = database() )
and (`table_name` = 'categories')
and (`column_key` = 'pri') ) as 'PrimaryKey'
from `categories`;
I used group_concat in the sub-query because it is highly possible to have a composite Primary Key - without group_concat you are likely to get an error.
use mysql_fetch_assoc for get column or value
$sql='select * from `categories`';
$query=mysql_query( $sql, $conn );
while($row = mysql_fetch_assoc($query))
{
foreach($row as $key => $value)
{
echo $key;//For print column name
echo $value;//For print value
}
}

passing array of values in sql select statement of where condition

$sql = "select id from table_name ";
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_assoc($result))
{
$data[] = $row[id];
}
/* $data contains id's fetched from sql query from db.now i want to pass this id's(array of values) in $data array one by one to below select query in where condition and obtain desired result for each id.My question is how to pass an array of values to the below select statement I dont know how to do this.Any help is greatly appreciated.*/
$query = "select * from table where id1 = $data[] ";
$query = "select * from table where `id1` in (" . implode(', ', $data) . ")";
You should use the cross database function in Moodle called get_in_or_equal()
list($where, $params) = $DB->get_in_or_equal($data, SQL_PARAMS_NAMED);
$sql = "SELECT *
FROM {table}
WHERE $id {$where}"
$records = $DB->get_records_sql($sql, $params);
You can use the IN clause.
When you are totally sure you only have numeric values in your $data array. You can do the following:
$query = "select * from table where id1 IN(" . implode(',', $data) . ")";
You can use this:
$comma_separated = implode(",", $data);
if ($comma_separated != "")
$query = "select * from table where id1 IN($comma_separated)";

MySQL contains variable

I have an array in PHP that is looping through a set of names (and a corresponding quantity). I would like to print the ones found in a MYSQL database table (to which I've succesfully connected). I'm currently using the code:
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
echo $quan." ".$row['name']. "\n";
}
}
For some reason, this only prints the last quantity and name in the array. Help?
For example, if the array has key-value pairs of {A-4, B-2, C-3}, and table contains {A, B, D} as names ... it'll only print "2 B".
Change the code to the following:
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
echo $quan." ".$row['name']. "\n";
}
}
}
You have to loop through the result. By the way, stop using mysql_query()! use MySQLi or PDO instead ( and be careful of SQL Injection ; you can use mysqli_real_escape_string() to handle input parameters ). For MySQLi implementation , here it is :
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysqli_query($query) or die(mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo $quan." ".$row['name']. PHP_EOL;
}
}
}
And rather "\n", I prefer using PHP_EOL ( as shown above )
And as the comment suggests, the SQL statement can be executed once, as follow:
$flipped_array = array_flip($arr); // flip the array to make "name" as values"
for($i = 0; $i < count($flipped_array); $i++) {
$flipped_array[$i] = '\'' . $flipped_array[$i] . '\''; // add surrounding single quotes
}
$name_list = implode(',', $arr);
$query = "SELECT * FROM table WHERE name IN ($name_list)";
// ... omit the followings
e.g. in $arr contains "peter", "mary", "ken", the Query will be:
SELECT * FROM table WHERE name IN ('peter','mary','ken')
sidenote: but I don't understand your query. You only obtain the name back from the query? You can check number of rows, or you can even group by name, such as:
SELECT name, COUNT(*) AS cnt FROM table GROUP BY name ORDER BY name
to get what you want.
UPDATE (again): based on the comment of OP, here is the solution :
$flipped_array = array_flip($arr); // flip the array to make "name" as values"
for($i = 0; $i < count($flipped_array); $i++) {
$flipped_array[$i] = '\'' . $flipped_array[$i] . '\''; // add surrounding single quotes
}
$name_list = implode(',', $arr);
$query = "SELECT name, COUNT(*) AS cnt FROM table WHERE name IN ($name_list) GROUP BY name HAVING COUNT(*) > 0 ORDER BY name";
$result = mysqli_query($query) or die(mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo $quan." ".$row['name']. ": " . $row['cnt'] . PHP_EOL;
}
}
The above query will show the name appearing in the table only. Names not in table will not be shown. Now full codes ( be cautious of SQL Injection , again )

php mysql query statement

I'm having a problem running a sql query using php.
$sql = "SELECT * FROM ".self::$table_name;
$result = mysql_query( $sql );
$r = mysql_fetch_array( $result );
print_r( $r );
die( '<br>'.$sql );
I have around 70 records in table but i'm only getting the first record.
see example.
Array ( [0] => site_url [setting_name] => site_url [1] => http://domain.com [value] => http://domain.com )
SELECT * FROM siteconfig
When I run the query in phpmyadmin. it works fine.
You have to make a loop to grab all the results:
$r = array();
while($junk = mysql_fetch_array($result)) $r[] = $junk;
print_r($r);
Do it like below:
$sql = "SELECT * FROM ".self::$table_name;
$result = mysql_query( $sql );
while($r = mysql_fetch_array($result)){
echo $r['col1']. " - ". $r['col2'];
// your stuff
}

Categories