How to combine two MySQL connections into one MySQL connection? - php

I have two MySQL connections for the same database in the one .php file.
Second connection is base on the result of First one.
How can I combine two connection into one ? Please help & teach me how to modify it ?
First connection:
<?php
header('Content-Type: text/html; charset=utf-8');
$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Logic data
$previous_page = ($_GET['crno'] - 1);
$next_page = ($_GET['crno'] + 1);
// select data
$sql = 'SELECT * FROM ComData WHERE com_no = '. $_GET['crno'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$pageTitle = $row['com_eng_name'] . $row['com_chi_name'];
$com_no = $row['com_no'];
$br_no = $row['br_no'];
$com_eng_name = $row['com_eng_name'];
$com_chi_name = $row['com_chi_name'];
$com_type = $row['com_type'];
$date_of_incorp = $row['date_of_incorp'];
$active_status = $row['active_status'];
$date_commenced_dormancy = $row['date_commenced_dormancy'];
$remarks = $row['remarks'];
$date_of_dissolution = $row['date_of_dissolution'];
$register_charges = $row['register_charges'];
$name_history = $row['name_history'];
$phone = $row['phone'];
$email = $row['email'];
$address = $row['address'];
$website = $row['website'];
$background = $row['background'];
$update_time = $row['update_time'];
}
} else {
echo "No Results";
}
$conn->close();
?>
Second connection:
<?php
header('Content-Type: text/html; charset=utf-8');
$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// select data for similar search
$string = "$com_eng_name";
$words = implode(' ', array_slice(explode(' ', $string ), 0, 2));
$sql = "SELECT * FROM ComData
WHERE com_eng_name REGEXP '$words'
ORDER BY com_no
DESC
LIMIT 20";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>CR No.</th><th>Company Name</th><th>Active Status</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["com_no"]."</td><td><a href='search.php?crno=".$row["com_no"]."' >".$row["com_eng_name"]." ".$row["com_chi_name"]."</a></td><td>".$row["active_status"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>

If those 2 pieces of code both exist in the same physical file then as the variable holding your connection in both cases is $conn you can just throw away the second attempt at making a connection to the database.
So just remove of comment out this code from the piece of code you called Second Connection i.e. this bit
$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Then remove this line
$conn->close();
from the piece of code you called First Connetion so you do not close the connection before the second piece of code runs.
However if in fact those 2 pieces of code are in seperate .php files. they have to stays the way they are.

It's not clear either if your two connection are in the same page or not, and if your two queries are execute sequentially or alternately.
Anyway, if the queries are on the same page or if you want put it in same page, sure you can use one only connection.
Start your script in this way:
header('Content-Type: text/html; charset=utf-8');
$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
then, if you have to performs both queries, continue in this way:
// Logic data
$previous_page = ($_GET['crno'] - 1);
$next_page = ($_GET['crno'] + 1);
// select data
$sql = 'SELECT * FROM ComData WHERE com_no = '. $_GET['crno'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
(...)
} else {
echo "No Results";
}
// select data for similar search
$string = "$com_eng_name";
$words = implode(' ', array_slice(explode(' ', $string ), 0, 2));
(...)
$conn->close();
Otherwise, if the queries are executed only on condition, after connection check continue in this way:
if( /* Your Condition Here */ )
{
// Logic data
$previous_page = ($_GET['crno'] - 1);
(...)
}
else
{
// select data for similar search
$string = "$com_eng_name";
(...)
}
If you want use connection in any different file, you can create a file dbconnect.php with this content:
$servername = "localhost";
$username = "abcabc";
$password = "12341234";
$dbname = "abc1234";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Then, in each file with db query, include it in this way:
header('Content-Type: text/html; charset=utf-8');
include( 'dbconnect.php' );
// Logic data
$previous_page = ($_GET['crno'] - 1);
(...)
header('Content-Type: text/html; charset=utf-8');
include( 'dbconnect.php' );
// select data for similar search
$string = "$com_eng_name";
(...)
etc...
Please note that, depending on 'dbconnect.php' file location, you can have to change include( 'dbconnect.php' ) with include( '/Full/Or/Relative/Path/dbconnect.php' ).

Related

I want to fetch time column from mysql database and to compare with current time

I want to fetch time column from mysql database and to compare with current time.
It should execute only if it matches with the current time.
Please tell me a MySql query or php code to do this.
I am new to php.
Try This:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$today = date("h:i a")
$sql = "SELECT * FROM Table_name WHERE SUBSTRING_INDEX(time, ' ', 2) = '".$today."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// execute you code
} else {
}
$conn->close();
?>
Try this: Updated Code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$today = date("h:i a")
$sql = "SELECT * FROM Table_name WHERE time = $today";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// execute you code
} else {
}
$conn->close();
?>

Why is there a space after exporting an excel using PHPExcel

Why after exporting an excel it does have space.I want to start in 1 the data I already clear the spaces on my codes but nothing happen. Thanks for helping me
<?php
function db_connect(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sti_lms";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
?>
<?php
/* File name : download_data_in_excel.php */
include('dbcon.php'); // include database connection file
$filename ="Books.xls";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment;filename='.$filename);
$sql = "SELECT * FROM book";
$conn = db_connect();
if($conn){
$result = $conn->query($sql);
echo "Accession\tCall_Num\tAuthor\tBook_Title\tCatalog\tbookcopies\tpublishername\tcopyrightyear\n"; // prints header line with field names
if ($result->num_rows > 0) {// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['acc_id']."\t".$row['callnum']."\t".$row['author']."\t". $row['book_title']."\t".$row['catalog']."\t".$row['book_copies']."\t".$row['publisher_name']."\t".$row['copyright_year']."\n";// prints each record with five fields in a row
}
}
}

Formatting fwrite output to a external file - Implode Error

The code I am working on queries a database through php and then placed the results into an array called CS. This array is then encoded so it can work with javascript. It is then supposed to edit the output so there is a newline after every row. The latter is where I have the problem. I get implode: invalid arguments passed every time regardless of how I edit the implode function.
Here is the code:
<?php
$servername = "*****";
$username = "****"; --> edited for privacy.
$password = "*******";
$database = "********";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// sql statement for tables and naming array to hold it in
$sql = "SELECT COURSE_ID FROM cs";
$result = $conn->query($sql);
$CS = array();
if ($result->num_rows > 0) {
// fill array with results
while($row = $result->fetch_assoc()) {
array_push($CS, $row);
}
} else {
echo "0 Results";
}
// encodes php array so it can be used in javascript
$json_array = json_encode($CS);
$conn->close();
// fills Computer_Science.js with the contents of the json_array and adds new lines in between
$json_array_lines = implode($json_array, "/n"); --> this line
$fp = fopen('..\js\DegreePlans\Computer_Science.js', 'w');
fwrite($fp, print_r($json_array_lines, TRUE));
fclose($fp);
?>
I'm at a loss on how to fix the error. Any help given will be appreciated.
I fixed it!
<?php
$servername = "*****";
$username = "****"; --> edited for privacy.
$password = "*******";
$database = "********";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// sql statement for tables and naming array to hold it in
$sql = "SELECT COURSE_ID FROM cs";
$result = $conn->query($sql);
$CS = array();
if ($result->num_rows > 0) {
// fill array with results
while($row = $result->fetch_assoc()) {
array_push($CS, $row);
}
} else {
echo "0 Results";
}
$conn->close();
//encode the array so it can be used in javascript and use regular expressions to format it.
$json_string = json_encode($CS);
$re = "/.,/";
$subst = "},\r\n"; --> right here!
$json_string = preg_replace($re, $subst, $json_string);
$fp = fopen('..\js\DegreePlans\Computer_Science.js', 'w');
fwrite($fp, print_r($json_string, TRUE));
fclose($fp);
?>

Mysqli to variable in PHP

I've been a few days working on my project, but just stay stuck a specific part.
My problem is that i like to get a value from the database (mysqli)
But i always receive a 0. So, no value.
This is my code:
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "dbname";
$serialkey = $_GET['hardwareSerial'];
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user_idSQL = "SELECT user_id FROM ss_devices WHERE serialkey = '$serialkey'";
$user_idResult = $conn->query($user_idSQL);
$user_id = $user_idResult;
The script should see what the userid, it is in equality with the specified serial number.
But when i take a serial number like: FJRI433. I always get a 0. But in the database has this serial number user_id: 3.
I hope someone can help me out whith this problem.
Thanks.
You are executing the query but not fetching any results.
The manual has plenty of examples of using mysqli :
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
//Do stuff with the next row.
}
}
Try this perhaps...
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "dbname";
$serialkey = $_GET['hardwareSerial'];
$conn=mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ( mysqli_connect_errno() ) {
die("Connection failed: " . mysqli_connect_error() );
}
$user_idSQL = "SELECT `user_id` FROM `ss_devices` WHERE `serialkey` = '$serialkey'";
if( $user_idResult = mysqli_query( $conn, $user_idSQL ) ) {
while ($row = mysqli_fetch_assoc($user_idResult)) {
echo $row['user_id'].'<br />';
}
}
mysqli_close( $conn );

Check MySQL DB for value

Hi guys im trying to check if a value(token) inside my MYSQL DB exists.
Main informations:
Table: Tokens
Column: Token
My latest try:
<?php
// DATABASE STUFF
$servername = "localhost";
$username = "userhere";
$password = "passhere";
$dbname = "zwinky";
$token = $_GET['a'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysql_query("SELECT * FROM Tokens WHERE Token = '$token'");
$matchFound = mysql_num_rows($result) > 0 ? 'yes' : 'no';
echo $matchFound;
?>
Does anyone have a idea?
If you are using mysqli_* then you can't use mysql_*
Try this one
<?php
// DATABASE STUFF
$servername = "localhost";
$username = "userhere";
$password = "passhere";
$dbname = "zwinky";
$token = $_GET['a'];
$con=mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
$result = mysqli_query($con,"SELECT * FROM Tokens WHERE Token = '$token'");
$matchFound = mysqli_num_rows($result) > 0 ? 'yes' : 'no';
echo $matchFound;
?>

Categories