Reputation: 3
Get this from error-message invalid query: No database selected, even though I have selected database in my template.php
This is the code im making right now. It's a table that displays users for the admin: anvandare.php:
$query = "select * from user";
$run = mysql_query($query);
if (!$run){
die('invalid query: ' . mysql_error());
}
while($row=mysql_fetch_array($run)){
$email = $row['email'];
$company = $row['company'];
$fname = $row['fname'];
$licensID = $row['licensID'];
$tel = $row['tel'];
?>
<td><?php echo $email; ?></td>
<td><?php echo $company; ?></td>
<td><?php echo $fname; ?></td>
<td><?php echo $licensID; ?></td>
<td><?php echo $tel; ?></td>
<td> ta bort </td>
</tr>
<?php } ?>
</table>
</div> <!-- Stänger jumbotron -->
</div> <!-- Stänger jumbotronbekraftat -->
</div> <!-- Stänger container -->
<?php
echo $navigation_admin;
echo $header;
?>
This is the databas.php
<?php
session_start();
session_regenerate_id();
$mysqli = new mysqli("localhost", "root", "", "Webbprojekt");
mysqli_set_charset($mysqli,"utf-8");
?>
How do I sort this problem out? Because in the include (template.php)
I have connected with my database.
Upvotes: 0
Views: 127
Reputation: 1667
In your database.php you have created connection using mysqli_() but in your .php you have used mysql_query($query); Instead of using mysql_ use mysqli_*
I mean to say use either mysql_() or mysqli_() throughout the project.As mysql_() are depreciated so use mysqli_()
Upvotes: 0
Reputation: 354
Your new code with PDO should be like as below
$db_con = new PDO('mysql:host=localhost;dbname=db-name', 'username', 'password');
$statement = $db_con->prepare("select * from user");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $row)
{
$email = $row['email'];
$company = $row['company'];
$fname = $row['fname'];
$licensID = $row['licensID'];
$tel = $row['tel'];
}
Upvotes: 0
Reputation: 447
<?php
$host="localhost"; $db="dbname"; $charset="utf8"; $user="root"; $pass="";
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);
?>
use this in your template for more secure, but u can use this for your project:
<?php
mysql_connect("localhost","root","pass");
mysql_select_db("dbname");
?>
Upvotes: 0
Reputation: 1381
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $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();
}
?>
use the above code to make database connection For more Info
http://www.w3schools.com/php/php_mysql_connect.asp
Upvotes: 1