Dynamically Query Mysql using PHP PDO and using % in Select - php

I have queried the database and got a list of database names that match my criteria. This is what I ran to get the information.
$sql = "SELECT DISTINCT tb.TABLE_SCHEMA
FROM
INFORMATION_SCHEMA.TABLES AS tb
INNER JOIN
INFORMATION_SCHEMA.TABLES AS tb2
WHERE tb.TABLE_NAME like '%OPTION%'
AND tb2.TABLE_NAME like '%USER%'";
$query = $handler->prepare($sql);
$query->execute();
$dbnames = $query->fetchAll(PDO::FETCH_COLUMN);
What I am trying to accomplish:
Now that I have the names, I need to run through each database so that I can get the list of websites, email of admin and user login. I know I can achieve this individually, but I am trying to do this dynamically with variables. The select statement below would run and give me my answer. However the prefix before the underscore in the FROM ysY6q8hmL7_options is different in each database.
SELECT option_value FROM `ysY6q8hmL7_options` WHERE `option_name` = 'home'
I tried this code but consistently get an error. How can I solve this problem. How can I run the queries dynamically without knowing the full name of each table. thank you.
foreach ($result as $val) {
$sql = "SELECT option_value FROM $val.%_options WHERE option_name = 'home'";
$query = $handler->prepare($sql);
$query->execute();
$dbnames = $query->fetchAll(PDO::FETCH_ASSOC);
printResultConsole($dbnames);

Your logic looks ok, but why do you have that percent sign in the table name ? That’s probably what is causing an error (whose message you should have shared, by the way).
Try this instead :
$sql = "SELECT option_value FROM " . $val . "_options WHERE option_name = 'home'";

Related

Use mysql_insert_id in single query

Ok, don't know if this is simple in practice as it is in theory but I want to know.
I have a single INSERT query were by in that query, i want to extract the AUTO_INCREMENT value then reuse it in the same query.
For example
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
$getId = mysqli_insert_id();
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
Apparently, am getting a blank value(I know because the mysqli_insert_id() is before the query, but I've tried all i could but nothing has come out as i want. Can some please help me on how to achive this
From my knoweldge this cant be done. Because no query has been run, MySQL is unable to return the ID of said query.
You could use a classic approach, pull the id of the previous record and add 1 to it, this is not a great solution as if a record is deleted, the auto increment value and the last value +1 may differ.
Run multiple queries and then use the insert_id (MySQLi is different to what you are using, you are best using $db->lastInsertId(); as mentioned in the comments.
Run a query before hand and store it as a variable;
SELECT auto_increment FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'tablename'
I strongly recommend Option 2, it is simply the cleanest and most reliable method for what you are looking to achieve.
It seems the value required for $display_type is :$display_type + (max(id) + 1).
In order to get the max_id you'll have to do this query before :
$sql = "SELECT id FROM articles ORDER BY id DESC LIMIT 1";
$result = mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
// $maxid[0] will contains the value desired
// Remove the mysqli_insert_id() call - Swap $getid by ($maxid[0] + 1)
// and u're good to go
N.B. update the name of ur primary key in the query $sql.
EDIT :
Assuming the weakness of the query and the quick resarch i did.
Try to replace $sql by (don't forget to Update DatabaseName & TableName values) :
$sql = SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
That Should do it . More info on the link below :
Stackoverflow : get auto-inc value
I don't think this can be done. You'll have to first insert the row, then update display_type, in two separate queries.
Thanks guys for your opinions, out of final copy, paste, edit and fix; here is the final working code(solution)
`
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
//Select AUTO_INCREMENT VALUE
$sql = "SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'chisel_bk'
AND TABLE_NAME = 'articles'";
$result = $mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
$getId = $maxid[0];
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
This happens to do the magic!!!
`

Mysql - SELECT columns from 2 tables using INNER JOIN error

This should be a basic question, but I haven't used Mysql for a very long time and forgot all the basic stuff. So SO programmers please bear with me.
I have 2 tables like this:
Table 1 (events): here
Table 2 (users): here
I would like to select all rows in the events table where event_invitees contains a username. I was able to do this using:
SELECT * FROM meetmeup_events WHERE event_invitees LIKE '%$username%'
Now I'd like to also select the event_invitees's photo from the users table (column called user_userphoto). My attempt to this was this:
$result = mysql_query("SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
WHERE event_invitees LIKE '%$username%'
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
This gave me an error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource
How can I do this? What am I missing? Can you give me some examples?
Thanks in advance! I'll be sure to accept the working answer!
You should change your mysql functions to either mysqli / PDO, although the problem seems to be the query itsef. Should be:
SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter
WHERE event_invitees LIKE '%$username%'
(the WHERE clause at the end)
Sql fiddle demo: http://sqlfiddle.com/#!2/852a2/1
Its just a matter of getting the query coded in the correct order, and you might like to make it a little more managable by using alias's for the table names
Try this :-
SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'
This of course assumes that all the column names are correct and the mu.user_username = me.event_inviter does in fact make sence because those fields are in fact equal
Additional Suggestion
You are not actually issuing the query for execution by mysql.
You have to do this :-
$sql = "SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'";
$result = mysql_query($sql);
$rows = array('mysql_count' => mysql_num_rows($result) );
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
Now in your browser using the javascript debugger look at the data that is returned. There should at least be a mysql_count field in it even if there is no 'meetmeup_user' array, and if it is zero you know it found nothing using your criteria.

PHP PDO result from query

I am trying to do a query in PHP PDO where it will grab a simple result. So like in my query I need it to find the row where the column group is 'Admin' and show what ever is in the group column. I know that we already know what it should be [Should be admin] but just need to get the query to work. Its only grabbing 1 row from my table, so will I need forsearch?
If I change WHERE group = 'Admin' to WHERE id = '1' it works fine. But I need it so it can be where group = 'admin'
$sql2 = "SELECT * FROM groups WHERE group = 'Admin'";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$users2 = $stm2->fetchAll();
foreach ($users2 as $row2) {
print ' '. $row2["group"] .' ';
}
Thanks
group is a reserved word in MySQL, that's why it's not working. In general it's a bad idea to use reserved words for your column and table names.
Try using backticks around group in your query to get around this, so:
$sql2 = "SELECT * FROM groups WHERE `group` = 'Admin'";
Also you should really use placeholders for values, because you're already using prepared statement it's a small change.
Edit: just to clarify my last remark about the placeholders. I mean something like this:
$sql2 = "SELECT * FROM groups WHERE `group` = ?";
$stm2->execute(array('Admin'));
try to use wildcard in your WHERE Clause:
$sql2 = "SELECT * FROM groups WHERE group LIKE '%Admin%'";
Since the value in your table is not really Admin but Administrator then using LIKE and wildcard would search the records which contains admin.

How to write an SQL statement for two variables, one carrying the table name, and the other the specific column in a table?

$select = $_POST['select'];
$search = $_POST['search'];
$sql = "SELECT * FROM '$select' WHERE $select = '$search'";
I have 2 variables carrying the aforementioned table name and column name. I want the user to be able to select a table name and then select a specific column and output the requested record.
I only have a problem with writing the sql statement. Thanks in advanced!
you may use the following query without any problem...
$sql="SELECT * from $select WHERE field_name='$search' ";
In the above query field_name is the that field name in which you want to search value of mattch the value.
you are using table instead of column
$sql = "SELECT * FROM '$select' WHERE $select = '$search'";
^^^^^^----//this should be column not table
this is bad idea you are doing. FULL of sql injection
switch to pdo or mysqli.
Escape your variables.

SQL select statement with blank in passing parameter

I'm trying to write a search function and am using multiple drop-down lists for search criteria.
i have a sql statement like
SELECT * FROM TABLE WHERE OFFICE='$office', NAME='$name', DEPARTMENT='$department';
Sometime I want to search with specific 'name' but without talking about 'department' and 'office'. But when I pass Blank '' to '$office' and '$department' it only return the person with no office and department. Is there anyway around to overcome it?
I tried to use '%' instead of blank but it didn't work as well.
I'm coding with php and MSSQL.
Thanks in Advance
If you want to work with wildcards, you dont need =, but LIKE. Unsure if this query works, but try it:
SELECT * FROM TABLE WHERE OFFICE LIKE '$office', NAME LIKE '$name', DEPARTMENT LIKE '$department';
Now you just have to check if the field is blank, if yes, replace it with a %. As i said, im unsure. I dont have a database availible at the moment for testing this.
for achieving this you have to write some php code like
$sql = "SELECT * FROM TABLE WHERE";
if(isset($office)){
$sql .= "OFFICE='$office',";
}
if(isset($name)){
$sql .= " NAME='$name',";
}
if(isset($department)){
$sql .= " DEPARTMENT='$department'";
}
You can easily do this as follow:
if(isset($office) && isset($department)){
$sql = "SELECT * FROM TABLE WHERE OFFICE='$office', NAME='$name', DEPARTMENT='$department'";
}
else{
$sql = "SELECT * FROM TABLE WHERE NAME LIKE '$name'";
}
mysql_query($connection, $sql);

Categories