Solved

I have already a connection, I do not want to open another connection to execute to mysql query.

Posted on 2016-08-16
5
69 Views
Last Modified: 2016-08-17
I have already a connection, I do not want to open another connection to execute to mysql query.

How can I rewrite the mysql script and php to execute the query?

// Create connection ( I already have one )
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//how can rewrite below code to execute the sql qurey without above connection script?
$sql = "SELECT isim FROM KullaniciBilgileri where uid='$uid'";
$result = $conn->query($sql);

// after successful connection and execution of sql I have this code below to write the results.

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["uid"]. " - İsim: " . $row["pwd"]. " " . $row["isim"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
0
Comment
Question by:Braveheartli
5 Comments
 
LVL 6

Expert Comment

by:Mukesh Yadav
ID: 41758942
If $conn already exists then use it as you are doing right now.

Just remove following code which connects to database:
// Create connection ( I already have one )
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

Open in new window

0
 
LVL 1

Author Comment

by:Braveheartli
ID: 41758947
I already did this, but it didn't work, because I use $conn variable in the if statement.
I think we should rewrite the if statement and the mysql sentence below

$sql = "SELECT isim FROM KullaniciBilgileri where uid='$uid'";
$result = $conn->query($sql);

// after successful connection and execution of sql I have this code below to write the results.

if ($result->num_rows > 0) {
0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 41758952
Every PHP script that connects to a MySQL database must have it's own connection code.  Why do you want to do without it?
0
 
LVL 29

Accepted Solution

by:
Olaf Doschke earned 500 total points
ID: 41758954
Since you also close the connection after being done, I actually doubt the connection already exists. The general reason for going through connecting before querying is, even though you have a Session, every request to a PHP script starts from scratch, you build up variables, objects and a MySQL Server connection to do things, then shut down. That's the nature of PHP, or any server side script.

One thing is correct, if you have a connection, you can also use it for multiple queries, like that:

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT isim FROM KullaniciBilgileri where uid='$uid'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["uid"]. " - İsim: " . $row["pwd"]. " " . $row["isim"]. "<br>";
    }
} else {
    echo "0 results";
}

$sql = "SELECT * FROM someothertable";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "something<br>";
    }
} else {
    echo "0 results";
}

$conn->close();

Open in new window

So in short, you simply reuse the still existing $conn variable to do another query. But that's only possible within the same PHP request, next time a browser request to your.php comes in, the $conn has to be redone, not only because you closed it, but since nothing lasts and stays but $_SESSION variables. And they can't persist a $conn, so don't even try $_SESSION['conn']=$conn;

For best practice you DRY (don't repeat yourself), so you put the connection into a PHP script you can require, also the general code to do a query could be made a script or even class. Obviously, the part of the code querying is very similar, and the query is just a parameter of $conn->query($sql). Only the inner part of what to do with the result differs, so a general routine would just return the result and not do anything with it. It seems you're at the point where you could use some knowledge about class design or at least structural programming, in detail user defined functions.

Bye, Olaf.
0
 
LVL 1

Author Closing Comment

by:Braveheartli
ID: 41758965
thank you Olaf,
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
change password links 7 74
PHP warning 4 30
Session timeout 5 15
How to loop bootstrap columns which contain database records 9 23
Foreword In the years since this article was written, numerous hacking attacks have targeted password-protected web sites.  The storage of client passwords has become a subject of much discussion, some of it useful and some of it misguided.  Of cou…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

861 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now