How to fetch a query with SHOW DATABASE LIKE statement? - php

I want to fetch some databases according to a specific name.
I have:
$sql="SHOW DATABASES LIKE `'%backup%'`";
$query=mysql_query($sql,$connect);
$row=mysql_fetch_assoc($query);
I need to fetch the databases in an array according to a specific name,but it gives me an error:
mysql_fetch_assoc() expects parameter 1 to be resource, boolean
Any idea how to do this?(And yes i know mysql is deprecated but i have to use it)

I have tested it
use:
SHOW DATABASES LIKE '%backup%'

here we go, its tested and working, but i will suggest you to use PDO, since mysql_* api is deprecated.
$sql="SHOW DATABASES LIKE '%backup%'";
$connect = mysql_connect("localhost", "root", "");
$query=mysql_query($sql,$connect) or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo $row[0]."<br/>";
}

Have you considered just listing all databases, then iterating through all results, matching them via regex/stripos and appending them into an array?
$sql="SHOW DATABASES";
$query=mysql_query($sql,$connect);
while ($row=mysql_fetch_assoc($query)) {
$var = preg_match("/backup/", $row['database'])
# Do whatever - append to array, echo, etc
}

EDITED
use mysql_select_db to select databases.see here http://php.net/manual/en/function.mysql-select-db.php
or you can use mysql_list_dbs but the problem is it will give all database. so using some loop you have to use your like operator to get what you want. see this:http://php.net/manual/en/function.mysql-list-dbs.php

Related

Get values from query and return as array

How could I return the values from this query as an array so that I can perform an action with the array?
$sql = mysql_query("SELECT username FROM `users`");
$row = mysql_fetch_array($sql);
How would I get the code to be like the following? Here, the user1 and user2 would be the usernames of the users selected from the above query.
$userarray = array("user1","user2");
Before I point out best practices, you need working code first. So I'll give you a simple solution first.
To run a query with the mysql extension the function is mysql_query, you can't pass the query text directly to mysql_fetch_array. Nextly mysql_fetch_array doesn't do what you think it does. mysql_fetch_array combines the functionality of mysql_fetch_row and mysql_fetch_assoc together by storing the key names of the resulting columns along with their numeric indexes. The mysql_fetch_array function does not return an array with all rows from your query. To get all rows from the query, you need to run mysql_fetch_array in a loop like so:
$sql = "SELECT username FROM `users`";
$result = mysql_query($sql);
if(!$result){echo mysql_error();exit;}
$rows=array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
print_r($rows);
Nextly, do note that the mysql_* functions are deprecated because the mysql extension in PHP is no longer maintained. This doesn't mean MySQL databases are deprecated, it just means the database adapter called mysql in PHP is old and newer adapters are available that you should be using instead, such as mysqli and PDO.
Next point, it is bad practice to rely upon short tags as it can be disabled by php.ini settings, always use either <?php ... ?> or <?= ... ?> for easy echoing which isn't affected by short tags.
Please read up on some mysqli or PDO simple examples to get started with one or the other. The mysqli extension is specific for MySQL while PDO (PHP Data Objects) is designed as a generic adapter for working with several kinds of databases in a unified way. Make your pick and switch so you're no longer using the deprecated mysql_* functions.
You would need to use a foreach loop to do it:
$userarray = [];
foreach($row as $single)
{
array_push($userarray, $single['username']);
}
and if can, try to use this MySQLi Class, it's very simple to get what you want from the database.
$db = new MysqliDb ('host', 'username', 'password', 'databaseName');
$userarray = $db->getValue('users', 'username', null);

Variables in Mysql Query

I am writing a PHP script in which i need to run a MySQL query. I opened the data connection and all such pleasantries are working fine. My only doubt is regarding the syntax of the following query, since it is not working. I have a php variable $post_id against which I am selecting from the database.
$query1="SELECT needer FROM needer_blood WHERE value_id='$post_id'";
$result=mysql_query($query);
$req_id=$result[0];
You are not fetching the result.
So try this
<?php
$query1="SELECT needer FROM needer_blood WHERE value_id='$post_id'";
$result=mysql_query($query);
while($row= mysql_fetch_array($result))
{
echo $row['needer'];//You can display your result like this.
}
Also mysql is depricated learn Mysqli or PDO.
For Mysqli function check this link http://php.net/manual/en/book.mysqli.php
For PDO function check this link http://php.net/manual/en/book.pdo.php
try this one, its better approach if you user SQL INJECTION
<?php
$query1="SELECT needer FROM needer_blood WHERE value_id='".mysql_real_escape_string($post_id)."'";
$result=mysql_query($query) or die(mysql_error()); // die only used in development , remove when you live this
$data = mysql_fetch_array($result) or die(mysql_error());
echo $req_id = $data['needer']; // $req_id = $data[0];
?>
Firstly, notice that your query variable is called $query1 and your mysql_query is using a variable called $query (variable mismatch?).
You can use mysql_fetch_assoc() to get an associative array from your query.
Using the following code should work, though you should do some checking to make sure that the $result[0] exists.
// Query String
$query1="SELECT needer FROM needer_blood WHERE value_id='$post_id'";
// Run the query
$result=mysql_query($query1) or die(mysql_error());
// Fetch Associative Array
$rows=mysql_fetch_assoc($result);
// Get result [0]: this could result in an error if your query result is empty.
$req_id=$rows[0];
Also, as others have pointed out, mysql is deprecated and you should update to MySQLi or PDO_MySQL if your server supports it. If not, change servers.
Also, as others pointed out, you should watch out for SQL injection. This StackOverflow answer adresses the issue well.

How to load a mysql array into an array without loop?

Simple question. lets say I run the following:
$results = mysql_query("SELECT * FROM table");
How can I load the mysql results array into a PHP array without doing a while loop? Example:
$mysql_results = array();
$results = mysql_query("SELECT * FROM table");
$mysql_results = mysql_load_all_results_into_array($results);
Thanks!
PHP's mysql_ library does not offer a method to "fetch all" rows without looping through the results-object using mysql_fetch_row() (or similar).
You can, however, update your code to use the mysqli library which contains a method named mysqli_result::fetch_all to perform the task you desire. Alternatively, you could update to use PDO which contains a similar method named PDOStatement::fetchAll.
As the mysql_ methods are being deprecated, updating to mysqli (or PDO) is the recommended way to go regardless.
You can't do that with mysql. You have to loop. You can do that with PDO
Use MySQLi extension please :
http://php.net/manual/en/mysqli-result.fetch-all.php
use: $values = mysql_fetch_array($results); but do check for success of your operation.... thus: while ($values = mysql_fetch_array($result)) { $msg = "Array gotten successfully."; }

Displaying all table names in php from MySQL database

Alright, so I'm fairly new to PHP and SQL/MySQL so any help is appreciated.
I feel like I took the right approach. I searched php.net for "MySQL show all table names", it returned a deprecated method and suggested using a MySQL query on SHOW TABLES [FROM db_name] [LIKE 'pattern'] I'm not sure what "pattern" means but, I searched for "SQL Wildcard" and got the "%" symbol. According to everything I found, this should work and output the table names at the end, but it does not. Any suggestions? Thanks in advance.
<?php
if ($_REQUEST["username"]=="coke"&&$_REQUEST["password"]=="pepsi"){
echo 'You have successfully logged in.';
echo '<br />';
echo 'These are your tables:';
echo '<br />';
$link = mysql_connect("sql2.njit.edu", "username", "password");
mysql_select_db("db_name") or die(mysql_error());
$result = mysql_query('SHOW TABLES [FROM db_name] [LIKE '%']');
echo $result;
}
else
echo 'You did not provide the proper authentication';
?>
I get no errors. The output is exactly what's echoed, but no table names.
The square brackets in your code are used in the mysql documentation to indicate groups of optional parameters. They should not be in the actual query.
The only command you actually need is:
show tables;
If you want tables from a specific database, let's say the database "books", then it would be
show tables from books;
You only need the LIKE part if you want to find tables whose names match a certain pattern. e.g.,
show tables from books like '%book%';
would show you the names of tables that have "book" somewhere in the name.
Furthermore, just running the "show tables" query will not produce any output that you can see. SQL answers the query and then passes it to PHP, but you need to tell PHP to echo it to the page.
Since it sounds like you're very new to SQL, I'd recommend running the mysql client from the command line (or using phpmyadmin, if it's installed on your system). That way you can see the results of various queries without having to go through PHP's functions for sending queries and receiving results.
If you have to use PHP, here's a very simple demonstration. Try this code after connecting to your database:
$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) { // go through each row that was returned in $result
echo($table[0] . "<BR>"); // print the table that was returned on that row.
}
For people that are using PDO statements
$query = $db->prepare('show tables');
$query->execute();
while($rows = $query->fetch(PDO::FETCH_ASSOC)){
var_dump($rows);
}
SHOW TABLES
will show all the tables in your db. If you want to filter the names you use LIKE and wildcard %
SHOW TABLES FROM my_database LIKE '%user%'
will give you all tables that's name include 'user', for example
users
user_pictures
mac_users
etc.
The brackets that are commonly used in the mysql documentation for examples should be ommitted in a 'real' query.
It also doesn't appear that you're echoing the result of the mysql query anywhere. mysql_query returns a mysql resource on success. The php manual page also includes instructions on how to load the mysql result resource into an array for echoing and other manipulation.
Queries should look like :
SHOW TABLES
SHOW TABLES FROM mydatabase
SHOW TABLES FROM mydatabase LIKE "tab%"
Things from the MySQL documentation in square brackets [] are optional.
you need to assign the mysql_query to a variable (eg $result), then display this variable as you would a normal result from the database.
Sure you can query your Database with SHOW TABLES and then loop through all the records but that is extra code lines and work.
PHP has a built in function to list all tables into an array for you :
mysql_list_tables - you can find more information about it at The PHP API page
//list_tables means database all table
$tables = $this->db->list_tables();
foreach ($tables as $table)
{
echo $table;
}

PHP MYSQL query shortcut?

If I am doing a PHP MYSQL select of a table using the where clause that will return only 1 result, is there a simpler way to do this:
$result = mysql_query("select * FROM cart WHERE ID='".$cartID."'") or die(mysql_error());
$cartrec = mysql_fetch_array($result);
Is the $cartrec = mysql_fetch_array($result); needed or could I just do:
$cartrec = mysql_query("select * FROM cart WHERE ID='".$cartID."'") or die(mysql_error());
or is there a better syntax to use?
mysql_query gets a result set (actually, a resource that refers to a result set) based on your query. This is the set of records that match your query.
mysql_fetch_array gets the first record from a result set, and returns it as an array.
So, up until you've called mysql_fetch_array, you haven't gotten the data in a usable format.
Side note: Consider using PDO
The fetch array is required, the mysql_query gets a result set (ressource), then mysql_fetch_array get's the element in the result set.
As a side note, be careful of SQL injections: http://en.wikipedia.org/wiki/SQL_injection
EDIT: Might be a bit more advanced that what you need, but it might be worth while looking into PDO: http://php.net/manual/en/book.pdo.php
Is the $cartrec = mysql_fetch_array($result); needed
Yes, otherwise you get a resource pointer not an result set (array).
or is there a better syntax to use?
Yes, MySQLi
No, but its pretty common for people to write their own function for this use case. It's usually named something like fetch_one($sqlString) or fetch_first($sqlString)
You could use this, but if the database structure were to change, it would be problematic
$row = mysql_fetch_row($result);
echo $row[0]; //column 1
echo $row[1]; //column 2
You may want to look at this http://www.php.net/manual/en/function.mysql-fetch-row.php

Categories