How to connect to database in real server - php

I am trying to connect to my database wich it created in PhpMyAdmin in my own server.
I write the code in a php file as below:
<?php
echo "welcome";
echo "<br>";
$conn = mysqli_connect("mydomainename.com:2080", "database_user_in phpmyadmin", "password of my database name", "name of database");
$result = mysqli_query( $this->conn, "SELECT * FROM `ad` WHERE 1");
while ( $row = mysqli_fetch_array( $result ) ) {
$ad_level = $row['ad_level'];
}
echo $ad_level;
?>
If I access to this page , its just return : welcome
I think that the error in the syntax of 'mysqli_connect' .... ist correct ??
have anyone any idea about this ?????
How do I do that? I googled a lot, but either I used the wrong keywords or there are no simple solutions on the internet. I hope somebody here can help me.
Best regards and thanks in advance, Fadel.

the real syntax is
mysqli_connect(host,username,password,dbname,port,socket);
so as you have written host name along with the port there must be an error.
you can refer the below link for more insite
http://www.w3schools.com/php/func_mysqli_connect.asp

Here is the general mySQL DB Connection Process:
<?php
// Create connection
$con = mysqli_connect("example.com", "peter", "abc123", "my_db");
// Check connection
if ( mysqli_connect_errno( $con ) ) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Try this
Use $conn in place of $this->conn
$result = mysqli_query($conn, "SELECT * FROM `ad` WHERE 1");
If you have error in mysqli connection the use die after this function like
$conn= mysqli_connect("myhost","myuser","mypassw","mybd")
or die("Error " . mysqli_error($conn));// use die here
Read this http://php.net/manual/en/function.mysqli-connect.php

I replaced
$conn = mysqli_connect("mydomainename.com:2080", "database_user_in phpmyadmin", "password of my database name", "name of database");
by this:
$conn = mysqli_connect("localhost", "database_user_in phpmyadmin", "password of my database name", "name of database");
but why !!! i have not any idea !! just it worck ... why ???? have anyone any idea about this ????

Try this way. I am currently using this method and its working perfect:
<?php
$server = "localhost";
$login = "root";
$pw = "myPassword";
$db = "myDatabase";
$con = mysql_connect($server, $login, $pw);
mysql_select_db($db, $con);
$qry = "select * from members where Username ='$Username' and Password = '$Password' and Status = 1" ;
$conQry = mysql_query($qry , $con);
?>
NOW YOU CAN FETCH YOUR DATA

Related

Checking already existing username or not MySQL, PHP

I Cannot Check whether the username already exist in database. I gone through existing questions that were answered here. None of them solved my problem. When i executes, it displays "Cannot select username from table", which i given inside die block. Code Is given below.
<?php
$username = $_POST['user_name'];
$password = $_POST['pass_word'];
$host = "localhost";
$db_username = "root";
$db_password = "";
$db_name = "my_db";
//create connection
$conn = #new mysqli($host, $db_username, $db_password, $db_name);
if (isset($_POST["submit"]))
{
# code...
//check connection established or not
if ($conn->connect_error)
{
die("Not Connected to DB");
}
else
{
$query = "SELECT 'usernamedb' FROM 'registration' WHERE usernamedb='$username'";
$result = mysqli_query($conn, $query) or die('Cannot select username from table');
if (mysqli_num_rows($result)>0)
{
$msg.="This username already exist. try Another !!";
}
else
{
$insert = "INSERT INTO 'registration'('id', 'usernamedb', 'password') VALUES ([$username],[$password])";
$insert_result = mysqli_query($conn,$insert) or die('INSERTION ERROR');
}
}
$conn->close();
}
?>
Hope someone will answer me.
First of all you should not use those unescaped queries.
But regarding your question you have an SQL error on your queries. You quoted table name. "FROM 'registration'" should be "FROM registration".

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. ;)

MySQL and PHP gives me null var

I make a random quote app, in which by pressing a button, i can load one random phrase. I created for this a MySQL database, and two php code.
I upload my two code in a web hosting, and the app is running!
But sometime it gives me "null" instead of the phrase. I don't know why.
I'm not very good with this.
What is probably the problem?
This is my index.php
require_once 'db.php';
$query = "SELECT * FROM quotes ORDER BY rand() LIMIT 1";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result)) {
print(json_encode($row['quote']));
}
And this is my db.php
// Create connection
$con=mysqli_connect("host","user","pass","a6361246_phrases");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
You can use the first three lines in your db.php file like this...
<?php
$host = 'localhost'; $db = 'database-name'; $user = 'database-user'; $pw = 'database-password';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
Don't forget to change database-name, database-user & database-password to your specific credentials.
Then using PDO get your phrase like this...
<?php
require_once 'db.php';
try {
$sql = "SELECT * FROM Quotes ORDER BY rand() LIMIT 1";
$query = $conn->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Could not get the data: " . $e->getMessage());
}
?>

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)) {

Error occurred ... no database selected

I'm trying to connect to a database, check a column for whether a value exists or not, then execute a function based on whether or not that value exists.
Here's my code.
$con = mysql_connect('localhost','root','','users');
$sql = "SELECT * FROM allUsers WHERE username = '".mysql_real_escape_string($_POST["username"]) . "'";
$result = mysql_query($sql,$con) or die("Error occurred in [$sql]: " . mysql_error());
$count = mysql_num_rows($result);
if ($count != 0){
echo "Username is already taken";
echo "$count";
mysql_close($con);
}
else{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
The thrown error is:
Error occurred in [SELECT * FROM allUsers WHERE username = 'Admin']: No database selected.
I'm almost entirely sure that it comes from the $result line, but haven't a clue as to why.
I feel like this is a simple solution, and I'm just missing something minor.
I'm very new to MySQL (today is my first day, actually), so please keep solutions as simple as possible.
You forgot to call mysql_select_db after connecting:
$con = mysql_connect('localhost','root','');
mysql_select_db('users', $con);
Unlike MySQLi or PDO, mysql_* libraries does not take database as argument on the connection string, however if you were to migrate to either MySQLi or PDO.
MySQLi:
$con = new mysqli('localhost', 'root', '', 'users');
PDO:
$con = new PDO('mysql:host=localhost;dbname=users', 'root', '');
In MySQLi your code would look like this:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$database = "users";
$con = mysqli_connect($host,$user,$pass,$database);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$stmt = $con->prepare("SELECT * FROM allUsers WHERE username = ? LIMIT 1");
$stmt->bind_param('s',$_POST["username"]);
if (!$stmt->execute())
die('Failed to excute with error ' . $con->error);
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if ($count > 0)
{
echo "Username is already taken.";
}
else
{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
I think your error is quite obvious, you need to specify the database you want.
mysql_select_db("databaseName", $con);
With that taken care of, please, please don't use mysql_ libraries the are vulnerable to SQL injection and will soon be removed.

Categories