starting with mysql on an ubuntu server php - php

I am new to mysql but have recently tried doing some tutorials to advance my knowledge. Anyways I installed mysql on my ubuntu server as well as phpmyadmin. They both seem to work just fine, I created a database in phpmyadmin called "test" as well as a table called "teddy".
I put data into the table and I can clearly see it through phpmyadmin.
Now when I try accessing this database via a php script on my ubuntu server, nothing happens. Literally nothing. It reacts the same way as if I had a syntax error (a quick load with nothing displayed).
This is my code... If anyone knows where my mistake is it would be much appreciated.
Thank you
<?php
$username='root';
$password='***';
$database='test';
#$db= mysqli_connect('localhost', $username, $password, $database);
if (mysqli_connect_errno())
{
echo 'Error: Could not connect';
exit;
}
$query= "select * from test";
$result= $db->query($query);
$num_results= $result->num_rows;
echo $num_results;
?>
EDITED (based on drew 010)
Problem was the table was not called test but teddy so putting in this code worked.
"SELECT * FROM 'teddy'";
$db= new mysqli('localhost', $username, $password, $database);
if (mysqli_connect_errno())
{
echo 'Error: Could not connect';
exit;
}
$query = "SELECT * FROM 'teddy'";
$result = $db->query($query);
if ($result) {
$num_results = $result->num_rows;
echo $num_results;
} else {
echo "Query failed: {$db->error}\n";
}
?>

$result= $db->query($query); is probably returning false for some reason.
Try:
$query = "select * from teddy";
$result = $db->query($query);
if ($result) {
$num_results = $result->num_rows;
echo $num_results;
} else {
echo "Query failed: {$db->error}\n";
}
See http://www.php.net/manual/en/mysqli.query.php#refsect1-mysqli.query-returnvalues

I don't use mysql but I'm guessing because you're using mysqli_connect. Try mysql_connect instead
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
http://php.net/manual/en/function.mysql-connect.php

#$db= mysqli_connect('localhost', $username, $password, $database);
should be
$db= new mysqli('localhost', $username, $password, $database);

Related

Mysql & Php Database connection error

When ever I use php to connect to my database I get a sudden error saying "database connection failed" is there anyway to fix this its for a login and register screen. Thanks to anyone who help...
<?php
$connection = mysqli_connect('localhost', 'root','','test');
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'test');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
<?php
//
require('database.php');
$connection = mysqli_connect('localhost', 'root','','test');
// If the values are posted, insert them into the database.
if (isset($_POST['Register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
//echo $query;
$result=mysqli_query($connection,$query);
if($result){
$smsg = "User Created Successfully.";
}else{
$fmsg ="User Registration Failed";
}
}
?>
Connection to a database with php requires 4 parameters (host, data base user, password, data base name, passwd), it's better nowadays to use db object instead of procedural "old" behaviour:
function connection(){
try{
//host, user, passwd, DB name)
$mysqli = new mysqli("localhost", $dbUser, $passwd, $dbName);
if (!$mysqli->set_charset("utf8")) $msg = "error charset mySQLi"; else $msg = "Set UTF-8 ok";
return $mysqli;
}
catch (Exception $mysqlin){
echo "Error stablishing connection with database ".$mysqlin->getMessage();
}
}
then you can connect easily as follows:
$sql = "SELECT * FROM users;";
if(!$result = connection()->query($sql)) echo "db query error"; else "query ok";
$rs = mysqli_fetch_assoc($result);
//do whatever and, to get next line of results:
if($rs!=''){
$rs = mysqli_fetch_assoc($result);
}
So you get a row of the results on $rs[] array.
EDIT: You'll need to apply security, this is a simple connection without regarding on it. Check mysqli bind params on php official webpage for it:
http://php.net/manual/en/mysqli-stmt.bind-param.php
Hope it helps

convert mySQL to mySQLi - using a class

The previous programmer had used a class called database that has the connection string and a bunch of functions. I now have to convert this to MySQLi and I am at a loss.
class database {
var $sql='';
var $result='';
function database( $host='localhost', $user, $pass, $db) {
// perform a number of fatality checks, then die gracefully
if (!function_exists( 'mysql_connect' )) {
//or die( 'FATAL ERROR: MySQL support not available. Please check your configuration.' );
exit();
}
bla..bla..bla - bunch of code goes here
function get_events_by_user($username) {
$sql = "SELECT event_id FROM user_events WHERE username = '$username'";
$result = mysql_query($sql);
return $result;
}
}
I tried
var $link=mysqli_connect('localhost', $user, $pass);
to use as
$result = mysqli_query($link,$sql);
but I can not use expression as a variable value and I don't know what else to do.
Thanks a bunch! :)
try to use this.
I think it solves your problem.
<?php
$link = mysqli_connect("localhost", $user, $pass, $databaseName);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
mysqli_set_charset($link, "utf8");
?>
just bring the $link in every query.
$link = mysqli_connect("localhost", $user, $pass, $db);
function get_events_by_user($username) {
$sql = "SELECT event_id FROM user_events WHERE username = '$username'";
$result = mysqli_query($link,$sql);
return $result;
}

Show all tables within given MySQL database

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>";
}

PHP SELECT * FROM not working

I am trying to query data from a table using the following script:
//connect file
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//connect file included above - ECHO tested and it is connected as $conn
$sql = "SELECT * FROM userInfo";
$results = $conn->query($sql);
if (!$results) {
printf("Errormessage: %s\n", $conn->error);
exit;
} else {
echo $row['username'];
}
UPDATE --
It now no longer tries to throw an error and seems to go to the else section; however, no echo - and the spelling is correct this time and the column is filled.
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["username"];
}
} else {
echo "0 results";
}
This now returns results. Thank you #Fred -ii- especially for your help on this.
Also thanks #jjczopek for the error checking advice!

Why can't i echo my results from MySQL in PHP?

I try to show every result that the current username has in the database,
but it won't work..
I've tried anything and ya'll are my last hope.
Thanks in advance!
I can not get any answer from my code here below:
<?php
session_start();
include_once('../inc/db/config.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT serverip, servername FROM servers WHERE username=".$_SESSION['user_name']."";
$results = mysqli_query($mysqli, $query);
if(mysqli_num_rows($results) >= 1)
{
while($row = mysqli_fetch_array($results))
{
echo "<hr/>";
echo "<a href='../s_info.php?server='" . $row['serverip'] . "><h2>" . $row['servername'] . "</h2>";
}
}
?>
This line looks suspect to me:
$query = "SELECT serverip, servername FROM servers WHERE username=".$_SESSION['user_name']."";
Try:
$query = "SELECT serverip, servername FROM servers WHERE username='{$_SESSION['user_name']}'";
You should be able to echo out that string as a test and run it separately in mysql command line/phpMyAdmin or whatever tool allows you to test sql statements. Insure that it returns a result.

Categories