php 'no database selected' but it is connected to the database - php

I have checked other questions with the same title but can't fix this. I have connected to the database though because the login works and I can display the user's username. Here is the relevent code, the second part is what's causing the error, thanks:
<?php require 'connection.php' ?>
<?php
session_start();
?>
<content>
<?php
//Select all from the categories table and order by the category title in ascending order (ASC)
$sql = "SELECT * FROM categories ORDER BY category_title ASC";
//$res = the result of the above query or die if error
$res = mysql_query($sql) or die (mysql_error());
if (mysql_num_rows($res) > 0) {
} else {
"<p>No categories availible</p>";
}
?>
</content>

Here is an example, for the visual of it.
<?php
$dbname = 'so_gibberish';
$dbuser = 'GuySmiley';
$dbpass = 'MyPassword';
$dbhost = 'localhost';
$link = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
mysql_select_db($dbname) or die("Could not open the db '$dbname'");
$test_query = "SHOW TABLES FROM $dbname";
$result = mysql_query($test_query);
...
...
mysql_close($link);
However, go with PDO
It is less sickly, full of robustness, and safer to say the least for binding:
Again, just a visual.
<?php
$theNum=102; // get from user, this is hard-coded
try {
$dbh = new PDO('mysql:host=localhost;dbname=so_gibberish;charset=utf8', 'GuySmiley', 'MyPassword');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare('SELECT id,smin,smax from ranges7
WHERE smin <= :theNum AND smax >= :theNum');
$stmt->bindParam(':theNum', $theNum, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// one row we hope
$data = "id: ".$row['id'] . ", smin: " . $row['smin'] . ", smax: " . $row['smax'] . "\n";
print $data;
}
$stmt = null;
// PDO closes connection at end of script
} catch (PDOException $e) {
echo 'PDO Exception: ' . $e->getMessage();
exit();
}
?>

Related

Getting error Record updated successfully Fatal error: Uncaught Error: Call to a member function fetch_assoc() on array

<?php
getdata();
function getdata(){
$server="";
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server;
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
?>
This bit makes no sense to me:
function getdata(){
$server=""; //<---------- set here
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server; //<---- sure you want to do this
//your basically setting $row[1] = '' on every iteration
//so your command below is "nslookup " because $server = ''
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
It seems to me this bit $row[1]= $server; is backwards.
But lets not forget the SQLInjection issues here:
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
Specifically this stuff:
function updatenslookup($url,$nsresult) {
// ....
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
// ....
}
The big issue with it is I can inject whatever I want into this table, then you take that data and shoot it right into
exec("nslookup ".$row[1], $result); //simplified $server = $row[1] + exec("nslookup ".$server)
So in theory I can (or may be able to) inject my own command line calls into exec, at least to some extent. I'm not sure all what someone could do with these issues, what the worst case would be, but I would avoid it in any case.
There is no way for me to know where the data for updatenslookup($url,$nsresult) comes from or if its clean, but it doesn't matter. One reason to prepare the sql is to have the security right where the issue is so you can clearly tell by looking at just the query if its safe or not. And you don't have to worry about missing some piece of data that could sneak in there.
You should use escapeshellarg at the very least, and clean up the SQL vulnerabilities by preparing your queries.
As far as this Call to a member function fetch_assoc() on array, I don't even see a call to fetch_assoc() in your code. Maybe I missed it but all I see is this $row = mysql_fetch_row($result); for reading data, which is procedural where you use the OOP in the other code . which is irritating .. but I get it, which is why I only use PDO now...
Etc..
I always feel bad when I shred up someones hard work, but I would be remiss not to mention such a big security hole.
Cheers.

PHP and SQL -- Select from database

I have a problem with this code. It has syntax error and I don't know what is it.
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
if (!$conn) {
die('Could not connect: ' . mysql_error());
$sql = 'SELECT id FROM users WHERE email=\"donat12#icloud.com\"';
echo $sql;
?>
There are some issue with the code. First you forgot to close the if condition over here
if (!$conn) {
And then you forgot to execute the sql query
the complete code would be like
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id FROM users WHERE email=\"donat12#icloud.com\"';
if ($result = $conn->query($sql)) {
while ( $row = $result->fetch_assoc()) {
$data[] = $row;
}
echo "<pre>";
print_r($data);
echo "</pre>";
}
$conn->close();
?>
There are two errors
You are missing } closing bracket after die
Mysql query is wrong.
So the code should be
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id FROM users WHERE email="donat12#icloud.com"';
echo $sql;

How do I reconnect my web pages on my website after updating to PHP 7 with a MySQL database 5.0.0?<?

I added the i updates to communicate with the database & now the page links don't work.
<?php
// Connect to database
$link=mysqli_connect('localhost', 'xxxxx', 'xxxxx');
mysqli_select_db($link, 'waddellc_PHRDB');
$sql = "SELECT * FROM quotes ORDER BY id";
$result = mysqli_query($link, $sql) or die(mysql_error());
$tenant_quotes = array();
$owner_quotes = array();
while($row = mysqli_fetch_array($result)) {
This should do the work, using PDO :
$servername = "localhost";
$username = "username";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=databaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(!is_null($conn)){
$stmt = $conn->prepare("SELECT * FROM quotes ORDER BY id");
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
}
I also think you need to update your database, it's quite old now.

Select SQL query is not working in PHP

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.

Mysqli wont allow table's to show when called on

As of recently ive been learning php and at that conjuntion in between where i have to now use Mysql in order to keep my bigger info table ogranized, well i wrote this code in order to show the tables (or so i think i did it right). im completely stumped because i can not see any of the displaying tables that i am calling on and the more ive tried the less i works so i was wondering if anyone can see a loop hole in my code or maybe im doing something wrong? or maybe everything ive done is wrong...?
`
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
?>
<?php
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<ul>
<?php
while($subject = mysqli_fetch_assoc($result)) {
?>
<li><?php echo $subject["menu_name"] . "(" . $subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
<?php
mysqli_free_result($result);
?>
</body>
</html>
<?php
mysqli_close($connection);
?>`
Have you forgotten the opening PHP tag at the beginning of your page?
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
Two things i think could be wrong.
Here is a correct implementation to compare. It could be the first PHP opening tag, i also added the default port to the connect statement, and added some try catches with error messages, these can tell if the connect or query is not working.
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
//original connect statement with a port added in
try {
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname , 3306);
} catch(Exception $e) { echo $e->getMessage(); }
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//Query looks fine, easier to trouble shoot when its one line, first get it working then break it up
$query = "SELECT * FROM subjects WHERE visible = 1 ORDER BY position ASC";
// This will try to fetch the result and give an error if it can't.
try { $result = mysqli_query($connection, $query);
} catch(Exception $e) { echo $e->getMessage(); }
if (!$result) { die("Database query failed"); }
?>
Is it alright if I alter some of your codes?
See this:
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<?php
/* ESTABLISH CONNECTION */
$connection=mysqli_connect("localhost","juliegri_AAlassa","YourPassword","juliegri_Aalassaly");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
/* START QUERY */
$result=mysqli_query($connection,"SELECT * FROM subjects WHERE visible='1' ORDER BY position ASC");
?>
<ul>
<?php
/* DO THE WHILE LOOP */
while($subject = mysqli_fetch_array($result)) {
?>
<li><?php echo $subject['menu_name'] . "(" . $subject['id'] . ")"; ?></li>
<?php
} /* END OF WHILE LOOP */
?>
</ul>
</body>
</html>

Categories