I'm trying to show all tables within a given MySQL database with php.
I'm very new to all this though and can't find a solution for it. Keeps giving an error 'no found file or directory'.
Anyone who can point out my mistakes here please?
Much appreciated!
<?php include "../inc/dbinfo.inc"; ?>
<html>
<body>
<h2>LIST TABLES FROM DATABASE</h2>
<?php
// Create connection
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
// Check connection
if ($conn->connect_error) {
die("Connection with the database failed: </br>" . $conn->connect_error);
}
echo "Connection established with the database! </br>";
// SQL to show tables
$sql = "SHOW TABLES FROM paperlessdb";
$result = mysql_query($sql);
if (!$result) {
echo "Database error, could not list tables.\n</br>";
echo 'MySQL error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "- {$row[0]}\n </br>";
}
mysql_free_result($result);
?>
First make up your mind, either use mysqli procedural or object orientated. Not a combination of both because its confusing. To avoid that all together use pdo instead.
Now properly connect to the database, you can select the database when connecting to it automatically:
const DB_DATABASE = 'paperlessdb';
$conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection with the database failed: </br>" . $conn->connect_error);
}
if($result = $conn->query('SHOW TABLES')){
while($row = $conn->fetch_array($result)){
$tables[] = $row[0];
}
}
print_r($tables);
Use below query,
$sql = "SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'paperlessdb'";
We are fetching the data from information_schema db which stores the meta data about our database.
You are using mysqli to connect to the database but use the depreciated mysql to query the database.
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)){}
mysql_free_result($result);
You should use mysqli_query() and mysqli_fetch_array() instead.
It'a a bit more complex but mysql is decrecated and remove as PHP 7 so no choice to jump ahead. Check out PDO ass well. I personally go for mysqli but most say pdo is more intuitive.
It should look more something like:
$result = mysqli_query($conn,$sql);
if(!$result){
die('MySQL error: ' . mysqli_error($conn));
}
while ($row = mysqli_fetch_row($result)) {
echo "- {$row[0]}\n </br>";
}
Related
I am trying to connect to and select data from an PostgreSQL server. I am able to connect to the server but my select query appears to be running an error. Any suggestions?
<?php
$conn = "host=#### port=5432 dbname=consolidated user=#### password=####";
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$dbconn = pg_connect($conn);
$result = pg_query($dbconn, "SELECT id FROM retailer_retailer;");
if (!$result) {
echo "An error occurred.\n";
exit;
}
while ($row = pg_fetch_row($result)) {
echo "ID: $row[0]";
echo "<br />\n";
}
?>
you miss the schema name right here, I assume you have table in public schema and your query should like-
$result = pg_query($dbconn, "SELECT id FROM public.retailer_retailer;");
If you have another schema then you can replace public with other schema name
I am having trouble with an SQL query that I have inserted into a piece of PHP code to retrieve some data. The query itself works perfectly within SQL. I am using the following PHP script.
I have the following objectives:
Connect to the existing database. This part works well.
Get data from the column 'Brand' of the table 'Transport' in $sql. This part is not working at this stage. echo ($sql) returns SELECT Brand FROM Transport WHERE Type = 'car'
Could you please let me know if you see the solution to this issue and if the remaining part of the code is correct. This is my f_sqlConnect()
function f_sqlConnect() {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!link) {
die('Could not connect: '.mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can not use'.DB_NAME.
': '.mysql_error());
}
}
/*This function cleans up the array to protect against injection attacks */
function f_clean($array) {
return array_map('mysql_real_escape_string', $array);
}
<?php
// Create connection
$link = f_sqlConnect();
// Getting data from the column Brand of the table Transport
$sql = "SELECT Brand FROM Transport WHERE Type = 'car'";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Brand: " . $row["Brand"]. "<br>";
}
} else {
echo "0 results";
}
$link->close();
?>
Here is the code, without seeing your f_sqlConnect(); mothod. This method should return connection string for DB in your case. But you can use following code this must work.
<?php
$servername = "Your_db_host";
$username = "your_db_username";
$password = "your_db_password";
$dbname = "your_DB_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Brand FROM Transport WHERE Type = 'car'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Brand: " . $row["Brand"];
}
} else {
echo "0 results";
}
$conn->close();
?>
NOTE: Object oriented way of mysqli, You can use procedural way too to connect and get data.
I trying to solve the UTF8 problem. So far i manage to test out and it works in mysqli connection.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tesddddt";
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysqli_set_charset($conn,"utf8");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM customer";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["uid"]. " - Name: " . $row["username"]. " " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
I manage to Insert and Select data with characters shown in it's language format correctly with the above coding.
However, when I try to do it in PDO , it shows 1 error when I insert data.
public function __construct(){
try {
$conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user_name, $this->db_pass);
mysqli_set_charset($conn,"utf8"); // <- added here
$this->conn=$conn;
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
I got this error
Warning: mysqli_set_charset() expects parameter 1 to be mysqli, object given in...
My php project is using PDO and hence need to get this work in PDO format. Anyone know how to settle this?
You try to connect via PDO and then change the charset via mysqli, without having a mysqli connection, that is what's causing the warning.
In PDO the charset usually is being specified within the connection string, like this:
$conn = new PDO("mysql:host=yourhost;dbname=yourdbname;charset=utf8");
I've installed XAMPP and have been attempting to interrogate my database using PHP although I keep getting the same error.
<?php
$servername = "localhost";
$username = "root";
$password = "secret";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform queries
$result = mysqli_query($conn,
"use edgeserver; call ShowAll") or die("Query fail: " . mysqli_error());
//loop the result set
while ($row = mysqli_fetch_array($result)){
echo $row[0] . " - " . + $row[1];
}
$conn->close();
?>
However this presents me with the following error:
Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\xampp\htdocs\amit\ShowAll.php on line 16
Query fail:
Mysql_error requires db connection to be passed. Try below:
mysqli_error($conn);
Thanks, it ended up being a combination of what you both said:
<?php
// Create connection
$conn = new mysqli('localhost', 'root', 'secret', 'edgeserver');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform queries
$result = mysqli_query($conn,
"call ShowAll") or die("Query fail: " . mysqli_error($conn));
//loop the result set
while ($row = mysqli_fetch_array($result)){
echo $row[0] . " - " . + $row[1];
}
$conn->close();
Great response, hopefully this will be the base to me developing some good code.
I think the problem is from use edgeserver; call ShowAll.
use edgeserver, where edgeserver is the database that you want to use.
call ShowAll - what you try to accomplish with this?
Your new mysqli must be like this:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
source: http://php.net/manual/ro/mysqli.construct.php
And on mysqli_query you must do the queries like "Select * from table".
I am trying to query the table bets but it seems it is not returning anything, even though there is data in it which matches the criteria
I'm not sure if I'm missing something completely obvious or not
Here is my code,
<?php
//Begin session
session_start();
//Get pool var
if(isset($_GET['pool'])) {
$_SESSION['pool'] = $_GET['pool'];
$pool = $_SESSION['pool'];
}
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Assign memberid
$memberid = $_SESSION['SESS_MEMBER_ID'];
echo "POOLNAME $pool<br>";
echo "MEMBERID $memberid<br>";
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$result = mysql_query($link,"SELECT * FROM bets WHERE member_id='$memberid'");
echo "RESULT $result";
echo "SQL executed<br>";
echo "Executing loop<br>";
while($row = mysql_fetch_array($result))
{
echo "test<br>";
$matchid = $row['match_id'];
$betAmount = $row['bet_amount'];
$teamname = $row['team_name'];
echo "$betAmount credits placed on team: $teamname for match: $matchid";
}
?>
You are mixing mysql and mysqli commands. You need to use one or the other, preferably mysqli, if possible.
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
should be:
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
And in mysqli_fetch_array() the first parameter is the mysqli result object (which you have correctly) and it requires a second parameter for the array it will return., MYSQLI_BOTH for example.
MYSQLI_BOTH will allow you to reference the array by the number indices or the column name
MYSQLI_ASSOC will allow reference from column names but not number indices and MYSQLI_NUM allows number indices.
so while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) would be what you want.
Also, do refer to the comment from Andy Lester about SQL injection, it is very important to sanitize input.