List all the tables in your MySQL database using PHP - php

I have a hard time trying to list all the tables in my database.
I tried
<?php
//Configuration
$dbname = 'local';
$user = 'root';
$host = '127.0.0.1';
$pass = '';
$date = date('Y-m-d');
$export_type = 'mysql'; // option : mysql | psql
$file_name = $date.'-portal';
$file_path = $file_name;
// Create connection
$conn = mysqli_connect($host, $user, $pass);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SHOW TABLES FROM $dbname";
$res = mysqli_query($conn, $sql);
if($res != false){
echo "Connected successfully";
$FILE = fopen("output.csv", "w");
$table = array();
while($row = mysql_fetch_array($res)){
$table[] = $row['0'];
}
foreach($tables as $table) {
$columns = array();
$res = mysqli_query($conn, "SHOW COLUMNS FROM $table");
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$columns[] = "$row[0]";
}
fwrite($FILE, implode(",", $columns)); fwrite("\n");
$resTable = mysqli_query($conn, "SELECT * FROM $table");
while($row = mysql_fetch_array($resTable, MYSQL_NUM)) {
fwrite($FILE, implode(",", $row)); fwrite("\n");
}
}
}else{
die(mysql_error());
}
?>
Result
if($res != false){
//.. everything in here never get executed
}
`$res` kept returning `false`.
What did I do wrong that could have lead to this ?

You can always execute the query:
Show tables;
After you selected database.
By the way you also can execute:
Show databases;
To list all of the databases your current user has permission to view.

Use db in your connection
mysqli_connect($host, $user, $pass, $dbname);
And use query like this
$sql = "SHOW TABLES";

You need to pass through your database in the connection script.
Like so:
$conn = mysqli_connect($host, $username, $pass, $dbname);
Then, when you want to pull rows from a table, you do it like this:
mysqli_query($conn, "SELECT rows FROM table");
One of the reasons this wasn't working for you was because you weren't passing through your database name through the connection. Also, rather than doing the above query, you selected a table from a database; rather than a row from a table.
Also, I noticed that you're using the mysql_* error output on the last line.

Here is a working version
Changes:
Added $dbname to mysqli_connect function
Added the backtick ` char between the table names, to avoid errors with reserved keyword from MySQL
Changed mysql_ functions to mysqli_
Close the file
Close the connection
Here is the code
NOTE: sorry I don't why, but when I pasted the code in the answer, all de code identation was messed up, even trying to indent it properly, I wasted like 10 minutes :(

Related

Echo a mysql column by php as an array [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
i want to fetch a mysql table named "my_table" column named "Email" contents as an array by php , so this is my code :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_table";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysql_query("SELECT * FROM my_table");
if ($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row['Email'];
}
echo join($data, ',');
?>
but this code returns me this error :
No database selected
but i've selected my table and database ...
and i know this code have some problems as mixing mysql and mysqli content but i dont know how to fix it i just want that array echo , if this code need to be fixed just guid me ,
how to solve this problem ? thanks in advance
Thanks to #Martin
my problem has solved i just changed the code by this way :
<?php
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "my_db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}
$result = mysqli_query($conn, "SELECT * FROM my_table");
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$data = array();
while ($row = mysqli_fetch_array($result))
{
$data[] = $row['Email'];
}
echo join($data, ',')
?>
You are conencting to a database here called "my_table":
$dbname = "my_table";
And then, in your SQL statement, you try connecting to a table called the same:
$result = mysql_query("SELECT * FROM my_table");
Are you sure this is the correct name for your database?
On PHPMyAdmin you can click "Databases" to view the Database names and then, when clicking on the db, it will give you a list of tables:
Image file of getting database views from tables in PHPMyAdmin

query returns nothing after a particular result size using MYSQLI_USE_RESULT [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 1 year ago.
I've read for larger result sets I must use the MYSQL_USE_RESULT option when querying. This I do. However, the below PHP page is accessed via ajax and I receive 0 results once the known number of results reaches ~800. Before I reach this threshold, queries execute splendidly.
All queries work fine in phpmyAdmin.
What am I doing wrong?
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$database = "mydb";
$mypassword = "expectedPassword";
$receivedPassword =$_POST["pwd"];
if ($receivedPassword != $mypassword) {
print "credential failure";
} else {
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
$myquery =$_POST["query"];
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
}
$res = $conn->query($myquery, MYSQLI_USE_RESULT);
$rows = array();
while ($r = mysqli_fetch_assoc($res)) {
$rows[] = $r;
}
$conn->close();
print(json_encode($rows));
}
?>
This had nothing to do with memory. Turns out the relation between larger query results and failing was purely statistical.
The real problem was that there were occasionally special characters in the data stored in the database. For some reason (perhaps someone can explain) PHP just stopped--no errors, no nothing when a special character was encountered. The field with the special character has collation: utf8_general_ci. I would have never thought this would be an issue... Perhaps someone can explain this as well.
Adding:mysqli_set_charset($conn,'utf8'); before the query fixed my problem entirely.
Edit your php.ini to let your server use more memory. Change memory_limit =128M to your desire value or add ini_set('memory_limit', '-1'); to your php code but this will tell the server to use all the memory it wants.
Try to use this:
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$database = "mydb";
$mypassword = "expectedPassword";
$receivedPassword =$_POST["pwd"];
if ($receivedPassword != $mypassword) {
print "credential failure";
} else {
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
$myquery =$_POST["query"];
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
$res = $conn->query($myquery, MYSQLI_USE_RESULT);
$rows = array();
while ($r = mysqli_fetch_assoc($res)) {
$rows[] = $r;
}
$conn->close();
print(json_encode($rows));
}
}
?>
In //Check connection you put if function. First statement is die() if $conn is error. In else statement of same if function you've puted nothing. Bottom part of code need to be inside else statement to work.
Try it.
try replace this
while ($r = mysqli_fetch_assoc($res)) {
$rows[] = $r;
}
on this
if ($result = $conn->store_result()) {
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$result->free();
}
You use MYSQL_USE_RESULT to recive all rows from table?

phpMyAdmin: one table in database work, another doesn't

I've created an app were you can register as a user. You can sign up and then you're in the database "myAppDataBase" in "firsttable". A second table contains a list of lets say other important users that I manually created in the PHPmyAdmin-Website/"App". This table is called "secondtable".
My code to get the data is as follows:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydatabas";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}else{
//Print ("successfully connected");
}
$query = "SELECT * FROM firsttable";
$result = mysqli_query($conn, $query) or die("Error: " . mysqli_error($query));
$num = mysqli_num_rows($result);
$rows = array();
while ($r = mysqli_fetch_assoc($result))
{
$rows[] = $r;
Print ("sf");
}
Print json_encode($rows);
mysqli_close($conn);
?>
The only thing i changed was this line: THIS WORKS
$query = "SELECT * FROM firsttable";
But when I change it to this it won't work anymore.
$query = "SELECT * FROM secondtable";
Any help?
Change this:
mysqli_error($query)
With this:
mysqli_error($conn) // with your connection
Explanation:
mysqli_error() function needs connection link identifier not your query as param.
Mysqli_error PHP Manual
I SOLVED IT! Somehow, my second wasn't encoded the right way. I simply added this coder and it worked:
mysqli_set_charset($conn, 'utf8mb4');
Thanks for all you help though. ;)

How do I get one row of data from mySQL table using php?

Here is an example of the current PHP code I have. I simply want to grab one row from the table, but it returns this error:
Call to a member function fetch_assoc() on a non-object
Any insight would be appreciated.
$pathname = "C:\Users\BL\Documents\GitHub\Moozik\music";
$files = scandir($pathname);
$server = "localhost";
$user = "root";
$pass = "";
while ($files[0] == "." || $files[0] == "..") {
array_shift($files);
}
print_r($files);
$song = $pathname . '\\' . $files[0];
$conn = new mysqli($server, $user, $pass);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT song_path FROM song_data";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()) {
$its = $row["song_path"];
printf($its);
}
mysqli_close($conn);
Point 1 :
You have mixed mysqli Object-oriented and Procedural methods...Use any one
Point 2:
$conn = new mysqli($server, $user, $pass);
// Here You missed database to be selected
Point 3:
$result = mysqli_query($conn, $sql); // Used procedural method But Connection is by Object Oriented method
here is a full object oriented method
$conn = new mysqli($server, $user, $pass, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT song_path FROM song_data";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$its = $row["song_path"];
echo $its;
}
$conn->close();
You can use
$row=mysqli_fetch_array($result)
You don't even have to use while since you wanna fetch only one row. IF you wanna fetch more than one row, then you can use the while.
You can use this.
$row=mysqli_fetch_row($result)
It will fetches the one row from result set..
Hope this will help.!

Query MySQL with PHP

I am trying to query a MySQL database with PHP and return the results as JSON. I'm new to PHP and web development so I'm not sure what I'm doing wrong. I've set up the database using MAMP. My parameters are being printed but I'm not getting the JSON. I've gotten this far with the help of a tutorial.
EDIT: I just went into phpMyAdmin to make sure it was working and when I click on Server:localhost:8889, a window pops up that says Error in processing request. Error code 404.
I'm thinking this is the problem, I'm just not sure why it isn't working. I may reinstall MAMP.
<?php
$user = 'root';
$password = 'root';
$db = 'TestDB';
$host = '127.0.0.1';
$port = '8889';
$first_name = filter_input(INPUT_GET, 'first_name');
$last_name = filter_input(INPUT_GET, 'last_name');
$membership_number = filter_input(INPUT_GET, 'membership_number');
echo $first_name;
echo $last_name;
echo $membership_number;
// Create connection
// $con = mysqli_connect("localhost", "root", "root", "TestDB");
// $con = mysqli_connect("localhost", "root", "root", "TestDB", "8889", $socket);
$link = mysqli_init();
$con = mysqli_real_connect($link, $host, $user, $password, $db, $port);
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = \'$first_name\' and LAST_NAME = \'$last_name\' and MEMBERSHIP_NUMBER = \'$membership_number\'";
$result = mysqli_query($con, $sql);
if(!$result) {
die('Query failed: ' . mysqli_error());
}
// Check for results
// if ($result = mysqli_query($con, $sql)) {
if($result) {
// If there are results, create results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
// while($row = $result->fetch_object()) {
while($row = mysqli_fetch_object($result)) {
// Add each row to the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo $tempArray;
echo $resultArray;
echo $result;
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
You need to change you $sql variable to remove the escapes on the single quotes. They register as part of the string because you are using double-quotes to wrap it. Basically, you're telling the database to run the query "SELECT * FROM NAME WHERE FIRST_NAME = \'John\' and LAST_NAME = \'Smith\' and MEMBERSHIP_NUMBER = \'VRX78435\'". This will error if you run it directly because the escape characters are not escaping.
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = '$first_name' and LAST_NAME = '$last_name' and MEMBERSHIP_NUMBER = '$membership_number'";
That should fix it for you.
There may also be an issue with your connection to the server. mysqli_query() uses the results of mysqli_connect() to run the query. mysqli_real_connect() only returns a boolean value, so it is invalid for this particular use (at least it failed to work on my server).
This would be a simple matter of replacing the $con and then you can drop the $link variable.
$con = mysqli_connect($host, $user, $password, $db, $port);
These changes, and assuming the $first_name, $last_name, and $membership_number are all valid, allowed your script to run for me, so I hope this helps.
Seems you are using procedural style coding
Instead of
while($row = $result->fetch_object()) {
You need mysqli_fetch_object in procedural style
while($row = mysqli_fetch_object($result)) {

Categories