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;
}
Related
I have searched all over the internet and have found various "helpful" tips about how to do a column sum with PHP and a MySQL table. The problem is that I can not get ANY of them to work.
Essentially I have a very simple database with 2 users. The table within the database is called users and each entry has a 'Name' and a 'Total Steps'. All I want to do is display the result of the total steps of each user and then a sum of their steps.
Here is my code:
<?php
$steps = mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users");
$row = mysql_fetch_assoc($steps);
$sum = $row['value_sum'];
?>
However, I get this error upon loading the page:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /nfs/nfs4/home/msnether/apache/htdocs/st.php
Since I don't know PHP or MySQL very well yet, this is quite frustrating and I would appreciate any help.
Heres the basics step for you if your a beginner in using php and mysql..
FIRST : SET UP CONFIGURATION FOR DATABASE USER,PASS,HOST
$conn = mysql_connect('database_server','database_username','database_password');
SECOND : Execute a database connection.
mysql_select_db($conn,'database name');
THIRD : Create a Query(you may insert your query here)..
$sql= mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users");
FINAL : SHOWN RECORDS USING MYSQL FUNCTIONS LIKE..
while($row = mysql_fetch_array($sql)){
echo $row['dabatase_columnname'];
echo $row['database_columnname'];
}
If you "Do not know PHP and Mysql well" then, knowing or die(mysql_error()) will be a pretty useful tool for you in the future. Just add it here, and see what mysql will make you understand politely.
$steps = mysql_query("SELECT SUM(Total_Steps) AS value_sum FROM users") or die(mysql_error());
I'm relatively new to php, and to this point I've been fine using the mysql_fetch_array function to echo values selected from the database. But now I want to be able to echo the results selected from multiple rows with the same username.
I was just wondering what the most efficient way of doing this was. I could manage to do it using a for loop and counting through each individual query, but I know there must be a more efficient way just using sql, or using a better oho function.
Thank you for the help.
Alex
while($row = mysql_fetch_array($result)) {
// process each row
}
I guess that's all you neeed - have a play and you should get your desired effect! It's best to do it in PHP..
Also you shouldn't use mysql_fetch_array anymore as it's deprecated. Use PDO or mysqli insted. More information you can find here
while($row = mysql_fetch_assoc($result)) {
} or
while($row = mysql_fetch_array($result)) {
}
and mysql_ functions are depreciated now onwards in mysql
SQL is used to query the database your using. PHP is used to format the output from the query. See the manual from PHP.net for more info php.net/manual/en/function.mysql-fetch-array.php . There is no way as far as I know to format the output in rows using SQL.
B.T.W. if this is new code I would advice you to use mysqli instead of mysql.
I just cannot figure out What is wrong with this query?
$q_u= "SELECT * FROM myTable where dd='$xx'";
$u = mysql_query($q_u, $conf) or die(mysql_error());
$row_u= mysql_fetch_assoc($u);
$dn = $row_u['d'];
The problem is the results are not being displayed when the values is passed into $xx.
Thanks
Jean
General debugging hints:
Output the query: echo $q_u; to see whether it makes sense (i.e. if $xx is okay, and doesn't get garbled somewhere)
Count the results using mysql_num_rows() - mysql_error() will catch only real errors, not empty results!
If there are results, dump them using var_dump($row_u) to see what columns you get
if, as it turned out here, no results are returned, no data in your database matches your condition. You'll need to look into the database to find out why.
Turn on the mysql general query log and look at what actually arrives in the database.
This is really getting frustrating. I have a text file that I'm reading for a list of part numbers that goes into an array. I'm using the following foreach function to search a database for matching numbers.
$file = file('parts_array.txt');
foreach ($file as $newPart)
{
$sql = "SELECT products_sku FROM products WHERE products_sku='" . $newPart . "'";
$rs = mysql_query($sql);
$num_rows = mysql_num_rows($rs);
echo $num_rows;
echo "<br />";
}
The problem is I'm getting 0 rows returned from mysql_num_rows. I can type the sql statement without the variable and it works perfectly. I can even echo out the sql statement from this script, copy and paste the statement from the browser and it works. But, for some reason I'm not getting any records when I'm using the variable. I've used variables in sql statements tons of times, but this really has me stumped.
Try trimming and mysql_real_escape_string on your variable.
Check the source code of what is being echoed out and try to copy and paste that into PHPMyAdmin or something similar.
file includes newlines in the array elements. This may explain why it works when you copy the browser output but not in the script. You can try either:
$file = file('parts_array.txt', FILE_IGNORE_NEW_LINES);
or:
$sql = "SELECT products_sku FROM products WHERE products_sku='" . trim($newPart) . "'";
Note: Even though you're importing from a file of your own making, you can never be 100% sure that inject-able data hasn't been inserted into it. You should make sure to properly escape any data with mysql_real_escape_string. Even better would be using PDO prepared statements instead.
Obviously your code does something different than you expect. Running a successful query, for one: you don't check the return value of the mysql_query call, so you cannot be sure the query executed ok.
My idea:
dump your sql statement from the foreach
check the return code of the mysql_query
What does your parts_array.txt file look like? Do SKU numbers contain the ' character?
Can you please try this:
$file = file('parts_array.txt');
foreach ($file as $line_num => $line)
{
$sql = "SELECT products_sku FROM products WHERE products_sku='$line'";
echo $sql;
$rs = mysql_query($sql);
$num_rows = mysql_num_rows($rs);
echo $num_rows;
echo "<br />";
}
You might want to check for a mysql_error. It sounds like you've already verified the variable and have copied the query into a database interface like PHPMyAdmin or Query Browser, but if you haven't, I would recommend that.
After, verify that a very basic query will work, like SELECT * FROM Products. That will tell you if there is a problem outside of the query.
Overall, I would say the strategy would be to break the problem down into possible problem areas, like database, connection, query, errors, etc. Try to eliminate them one at a time until the problem is apparent. In other words, list the possibilities and cross them off one at a time.
I've encountered problems like this before; the trick is usually to start echoing things until you see the problem, and don't work off of assumptions.
I know this is pretty old now- but I'd like to help out others who may also be facing a similar problem with SQL statements that need to contain a potentially infinite number generated search parameters.
The code in the askers question is perfectly valid (for the avoidance of doubt) [see below]:
$file = file('parts_array.txt');
foreach ($file as $newPart)
{
$sql = "SELECT products_sku FROM products WHERE products_sku='" . $newPart . "'";
$rs = mysql_query($sql);
$num_rows = mysql_num_rows($rs);
echo $num_rows;
echo "<br />";
}
Their problem lies in the formatting of their text file ('parts_array.txt'). The root cause of the issue can be tracked down by dumping the information sent back by the server. Alternatively- they can try writing an SQL query in PHPMyAdmin and pasting in some or all of the data in their text file. MySQL will happily torment them until they find the problem.
For those trying to implement a variable based SQL query- the above is the way to go.
If you are trying to get data from an array, instead of a text file- you could do something like the following:
foreach ($array as $array_stuff)
{
$search_query = "SELECT * FROM table WHERE id='" . $array_stuff . "'";
$rs = mysqli_query($database_connection, $search_query);
$table_rows = mysqli_fetch_assoc($rs);
echo $table_rows['id']." - ".$table_rows['desc'];
echo "<br />";
}
/* free result set */
mysqli_free_result($rs);
This would output your data like this:
1001 - data 1 1002 - data 2 1003 - data 3
Note: The use of "mysql" functions are actively discouraged by MySQL. Therefore the second example I have given above is more up-to-date with current technologies, and using "mysqli" instead.
Also important
If you are here from a Google search as a result of trying to get data from a database, using a complex SQL query- you might have already tried to do something like the example below (or be considering it).
Do not attempt to write a variable based SQL query as per the example below. It won't work and will be incredibly frustrating.
Based on recent technological advancements- the second example I have given (using "mysqli") is the correct way (if there is one) to achieve this.
Bad example:
if ($search_result = mysqli_query($dbh1, "SELECT FROM sic_codes WHERE id = (".foreach ($_POST['SIC_Codes'] as $sic_codes) {echo "'".$sic_codes."' OR id = '',";})) {
/* fetch associative array */
while ($search_row = mysqli_fetch_assoc($search_result)) {
echo $row["id"]." - ".$row["desc"]."<br/>";
}
I see I can get a MySQL database defined encoding in PHP using the function mysql_client_encoding(...), but is there a way to get a MySQL table defined encoding in PHP?
I see no easy way to retrieve this info. The best I could do is to do a "SHOW CREATE TABLE ;" and parse the answer:
<?php
$link = mysql_connect('localhost', 'account', 'passwd');
mysql_select_db('my_base');
$q = mysql_query('show create table my_table;');
$row = mysql_fetch_assoc($q);
preg_match("/CHARSET=(.*)/", $row['Create Table'], $matched);
echo "Table was created with charset " . $matched[1];
Which gives me:
Table was created with charset utf8
Note that charset may not be present if your table was not created with this info.
I am using SHOW CREATE TABLE query, but never from PHP.
Because I can't imagine if I ever need to run it from PHP. SET NAMES can serve any possible case.
Note that mysql_client_encoding() returns not database encoding. It's client encoding, as it says
As far as I know the encoding is defined on a per database basis in MySQL and not per table.