SQL not working unless multiple db_connect(); statements - php

In the past I've had no issues using one simple:
$link = db_connect();
in a single file with multiple SQL commands like so:
$sql = "UPDATE table SET...";
$sql_result = mysql_query($sql, $link)
or die("Couldn't execute query.");
$sql2 = "UPDATE table2 SET...";
$sql_result2 = mysql_query($sql2, $link)
or die("Couldn't execute query.");
Now any new file I create won't work without multiple/separate db_connects. For example:
$link = db_connect();
$link2 = db_connect();
$sql = "UPDATE table SET...";
$sql_result = mysql_query($sql, $link)
or die("Couldn't execute query.");
$sql2 = "UPDATE table2 SET...";
$sql_result2 = mysql_query($sql2, $link2)
or die("Couldn't execute query.");
The old files with multiple mysql_queries referencing a single db_connect(); are still working fine. What could have changed?
Thanks.
Updated to include the db_connect(); function:
function db_connect($db="database", $host="localhost", $user="user", $p="password") {
$dbcnx = #mysql_connect($host, $user, $p);
if (!$dbcnx)
{
echo( "<p>Unable to connect to the database server at this time.</p>" );
exit();
}
$database = #mysql_select_db($db, $dbcnx);
if (!$db)
{
echo "<p>Unable to locate the database at this time.</p>";
exit();
}
return $dbcnx;
}

If you want to have $links separated, add true as fourth mysql_connect() parameter:
$dbcnx = #mysql_connect($host, $user, $p, true);
Additionally if you want to use different connections (different databases, users, passwords), you need to explicitly pass parameters to db_connect() second time:
$link2 = db_connect('database2', 'whateverthehost', 'user2', 'andhispassword');

What you have posted looks fine unless you have something unset() ing $link, assigning it a value, or something else that is making $link no longer pointing to the database.

Related

how to use multiple database in opencart?

I have two project, first one in Yii and another in Open cart, I need use both DB in a project, in Yii site I have complete, now I have a issue in open cart so please explain how to use multiple database in open cart?
You can use multiple database something like this:
// Define database
$host = 'localhost';
$db1 = 'username1';
$pwd = 'pass';
$db2 = 'user2';
$pwd2 = 'pass';
$con1 = mysql_connect($host, $db1, $pwd) or die ('Error connecting to mysql');
$con2 = mysql_connect($host, $db2, $pwd2) or die ('2nd Db Error connecting to mysql');
$db_name1 = '`mydatabase`';
mysql_select_db($db_name, $con1);
$db_name2 = '`mydatabase2`';
mysql_select_db($db_name2, $con2);
This is your database actions:
$result = mysql_query("Select * from ......", $con1) or die(mysql_error());
$result = mysql_query("Select * from ......", $con2) or die(mysql_error());

List all the tables in your MySQL database using PHP

I have a hard time trying to list all the tables in my database.
I tried
<?php
//Configuration
$dbname = 'local';
$user = 'root';
$host = '127.0.0.1';
$pass = '';
$date = date('Y-m-d');
$export_type = 'mysql'; // option : mysql | psql
$file_name = $date.'-portal';
$file_path = $file_name;
// Create connection
$conn = mysqli_connect($host, $user, $pass);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SHOW TABLES FROM $dbname";
$res = mysqli_query($conn, $sql);
if($res != false){
echo "Connected successfully";
$FILE = fopen("output.csv", "w");
$table = array();
while($row = mysql_fetch_array($res)){
$table[] = $row['0'];
}
foreach($tables as $table) {
$columns = array();
$res = mysqli_query($conn, "SHOW COLUMNS FROM $table");
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$columns[] = "$row[0]";
}
fwrite($FILE, implode(",", $columns)); fwrite("\n");
$resTable = mysqli_query($conn, "SELECT * FROM $table");
while($row = mysql_fetch_array($resTable, MYSQL_NUM)) {
fwrite($FILE, implode(",", $row)); fwrite("\n");
}
}
}else{
die(mysql_error());
}
?>
Result
if($res != false){
//.. everything in here never get executed
}
`$res` kept returning `false`.
What did I do wrong that could have lead to this ?
You can always execute the query:
Show tables;
After you selected database.
By the way you also can execute:
Show databases;
To list all of the databases your current user has permission to view.
Use db in your connection
mysqli_connect($host, $user, $pass, $dbname);
And use query like this
$sql = "SHOW TABLES";
You need to pass through your database in the connection script.
Like so:
$conn = mysqli_connect($host, $username, $pass, $dbname);
Then, when you want to pull rows from a table, you do it like this:
mysqli_query($conn, "SELECT rows FROM table");
One of the reasons this wasn't working for you was because you weren't passing through your database name through the connection. Also, rather than doing the above query, you selected a table from a database; rather than a row from a table.
Also, I noticed that you're using the mysql_* error output on the last line.
Here is a working version
Changes:
Added $dbname to mysqli_connect function
Added the backtick ` char between the table names, to avoid errors with reserved keyword from MySQL
Changed mysql_ functions to mysqli_
Close the file
Close the connection
Here is the code
NOTE: sorry I don't why, but when I pasted the code in the answer, all de code identation was messed up, even trying to indent it properly, I wasted like 10 minutes :(

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

Is it possible to connect to two different mysql databases?

I have 2 databases that I need to connect with but I don't know how to put the query in my code.
I have 2 pages of code. 1 for the form and the other to display the data after we have filled out the form. Will I need to put a new query on both pages or neither?
When I try to put a second connection on both pages, the whole page isn't working.
The connection I have made looks like this for both pages:
<?php
session_start();
include('conn.php');
include('connection2.php');
?>
For second database:
<?php
define('DB_HOST2','localhost');
define('DB_USER2','root');
define('DB_PASSWORD2','');
define('DB_NAME2','smile2');
$dbc = #mysql_connect(DB_HOST2,DB_USER2,DB_PASSWORD2) OR Die ('Could not connect to MySQL: '. mysql_error());
#mysql_select_db (DB_NAME2) OR Die ('Could not select database: '. mysql_error());
?>
For first database:
<?php
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_NAME','smile');
$dbc = #mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) OR Die ('Could not connect to MySQL: '. mysql_error());
#mysql_select_db (DB_NAME) OR Die ('Could not select database: '. mysql_error());
?>
How can I make #mysql_* change to:
<?php
//connect
mysql_connect("localhost", "user", "password");
//select first database
mysql_select_db("database_1");
//do query
mysql_query("SELECT * FROM `table` WHERE `field` = 1");
//select second database
mysql_select_db("database_2");
//do query on other database
mysql_query("SELECT * FROM `other_table` WHERE `field` = 2");
//you might wanna switch back to the first database
mysql_select_db("database_1");
?>
You can use the PHP function mysql_select_db to switch between databases. Like so:
<?php
//The preferred way:
//connect
mysqli_connect("localhost", "user", "password");
//select first database
mysqli_select_db("database_1");
//do query
mysqli_query("SELECT * FROM `table` WHERE `field` = 1");
//select second database
mysqli_select_db("database_2");
//do query on other database
mysqli_query("SELECT * FROM `other_table` WHERE `field` = 2");
//you might wanna switch back to the first database
mysqli_select_db("database_1");
//The old way
//connect
mysql_connect("localhost", "user", "password");
//select first database
mysql_select_db("database_1");
//do query
mysql_query("SELECT * FROM `table` WHERE `field` = 1");
//select second database
mysql_select_db("database_2");
//do query on other database
mysql_query("SELECT * FROM `other_table` WHERE `field` = 2");
//you might wanna switch back to the first database
mysql_select_db("database_1");
?>
<?php
class manageDB{
private $dbStatus = false;
private $mode = 'debug';
private $curCon = 'db1';
private $db = '';
private $con = '';
private $details = array(
'db1'=>array(
'server'=> '',
'user' => '',
'pass' => '',
'db' => ''
),
'db2'=>array(
'server'=> '',
'user' => '',
'pass' => '',
'db' => ''
)
);
//Init object
function __construct() {
$this->curCon = ($GLOBALS['isDebug']) ? 'db1' : 'db2';
}
public function defineDB($options, $type){
if(empty($type)){
$this->curCon = 'db1';
$this->details[$this->curCon]['server'] = $options['server'];
$this->details[$this->curCon]['user'] = $options['user'];
$this->details[$this->curCon]['pass'] = $options['pass'];
$this->details[$this->curCon]['db'] = $options['db'];
$this->con = null;
} else {
$this->curCon = $type;
}
$this->returnDB = FALSE;
if($this->dbStatus == TRUE) $this->open();
}
public function open(){
$this->con = mysql_connect($this->details[$this->curCon]['server'], $this->details[$this->curCon]['user'], $this->details[$this->curCon]['pass']);
if (!$this->con) { die('Could not connect: ' . mysql_error()); };
mysql_select_db($this->details[$this->curCon]['db'], $this->con);
$this->dbStatus = true;
}
public function close(){
mysql_close($this->con);
unset($this->connectStatus);
$this->dbStatus = false;
}
public function changeDB($db){
if($this->details[$this->curCon]['db'] != $db) mysql_select_db($db, $this->con);
$this->returnDB = TRUE;
return $this;
}
public function qry($query) {
$args = func_get_args();
if(count($args) > 1){
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
}
$result = mysql_query($query);
//Check if we need to return to default table
if(isset($this->returnDB)){
mysql_select_db($this->details[$this->curCon]['db'], $this->con);
$this->returnDB = FALSE;
}
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
}
public function checkStatus(){ echo $this->dbStatus; }
};
$db = new manageDB();
?>
Usage:
for normal operations use
$select = $db->query(...);
to switch database use
$select = $db->changeDB('db_name')->query(...);
easily done one step at a time, like here:
<?php
$link = mysql_connect("localhost", "mysql_user","mysql_password")
or die("Could not connect to MYSQL");
$selected_db = mysql_select_db('Database_Name', $link)
or die ('Sorry, could not connect to Database');
echo 'Connected successfully';
mysql_close($link);
?>
then the second one as:
<?php
$link = mysql_connect("localhost", "mysql_user","mysql_password")
or die("Could not connect to MYSQL");
$selected_db = mysql_select_db('Database_Name', $link)
or die ('Sorry, could not connect to Database');
echo 'Connected successfully';
mysql_close($link);
?>

Categories