Using php I need to have 2 different connections to the database - php

I have a need to copy some rows from a database to a different database. I am experiencing difficulty. I have found several methods except none of the seem to work. The php version I am using is 5.4.
Both connections are in the same server, however everything else is different
This is the php code that I have found and it doesnt seem to work at all, I am unable to select from the first database
// Create connection
$wpdb = mysql_connect($servername, $username, $password);
// Check connection
if ($wpdb->connect_error) {
die("Connection failed: " . $wpdb->connect_error);
}
echo "Connected local successfully\n";
//$starttime = date("h:i:sa");
$mydb = mysql_connect('localhost','dbname','dbpassword', true);
// Check connection
if ($mydb->connect_error) {
die("Connection failed: " . $mydb->connect_error);
}
echo "Connected to Integrity successfully\n";
mysql_select_db($database, $wpdb);
mysql_select_db('wordpress_0', $mydb);

you can try with PDO.that provide a common interface to talk with many different databases.
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user',
'password');

I refuse to offer support for mysql_ syntax, so I'll offer the upgraded version.
Almost entirely copied from the php manual... http://php.net/manual/en/mysqli.select-db.php
Code:
/* attempt and check connection including first database selection "test" */
if (!$mysqli = new mysqli("localhost", "root", "", "test")) {
// never show the actual error to the public
echo "<div>Database Connection Error: " , $conn->connect_error , "</div>";
exit();
}
/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
// never show the actual error to the public
echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {
echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
$result->close();
}
/* change db to "mysql" db */
$mysqli->select_db("mysql");
/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
// never show the actual error to the public
echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {
echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
$result->close();
}
$mysqli->close();
Output:
Default database is: test
Default database is: mysql

Related

basic mysql data extraction using php

I've looked all over here. Please be patient as I am new to php and mysql.
I got WAMPP installed & seems to be working OK. I created a simple "test" database from phpMyAdmin and "firsttable" in that. I can do a simple connect using example from w3schools, but trying to select & display data I entered only throws back errors.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Connect
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT reference, firstname, lastname, room FROM firsttable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["reference"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "room:" . $row["room"]. "<br>";
}
} else {
echo "0 results";
}
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
First off, I get a parse error on line 17. The one that reads:
if ($result->num_rows > 0) {
The error says: Trying to get property of non-object.
I tried wrapping the whole php code in tags and saving it as html, but then it appeared that no row data was ever found.
I am able to use very simple code that connects successfully. I can confirm the database is in there, so is the table, and the contents I added to it.
Please, what am I doing wrong?
You need to specify the database when you connect:
$database = 'test';
$conn = mysqli_connect($servername, $username, $password, $database);
where $database is the name of your database (test in this case). MySQL doesn't know which database your table resides in without you telling it.
In addition, you should always include error checking for your database connection (you have two of these, you don't need the last one) as well as any queries. Sans this, you can check your error logs for more information when something fails.

Why this PHP Code won't add the data to the MySQL DB?

I am brand new in PHP / MySQL.
I got this code from
http://www.johnmorrisonline.com/how-to-insert-form-data-into-a-mysql-database-using-php/
(great tutorial by the way) and used it. The problem is that it runs smoothly (Got no errors) but it just won't add the new row to the database. I tried to simplify the code to figure it out. If i run the query on PHPMyAdmin it works ok (it adds a new row) but from browser (php script) won't.
I cant tell what's wrong.
I am using MAMP on my MBP computer.
Thanks so much
Rafa
Here's the code:
<?php
$mysqli = mysqli_init();
if (!$mysqli) {
die('mysqli_init failed');
}
if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!$mysqli->real_connect('localhost', 'root', 'root', 'procedimientos')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . $mysqli->host_info . "\n";
// Insert our data
$sql = "INSERT INTO PROCEDIMIENTOS (`RUT`) VALUES ('1587');";
$insert = $mysqli->query($sql);
// Print response from MySQL
if ( $insert ) {
echo "Success!";
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
$mysqli->close();
?>
You have to add $mysqli->commit(); before $mysqli->close(); to persist your changes to the DB.
You have this on top of your code:
if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
In other words, you're wrapping everything you do against MySQL server inside a transaction.
Your options are:
Do not start transactions automatically by default (and do it manually whenever you actually need them)
Commit the transaction on success

Converting from mysql to mysqli and getting Fatal error: Cannot use object of type mysqli as array

I am working on converting some PHP code from mysql to mysqli. I have created an error and am unable to understand how to fix it. Any suggestions would be greatly appreciated.
The code looks like this:
<?php
include ("admin/includes/connect.php");
$query = "select * from posts order by 1 DESC LIMIT 0,5";
$run = mysqli_query($conn["___mysqli_ston"], $query);
while ($row=mysqli_fetch_array($run)){
$post_id = $row['post_id'];
$title = $row['post_title'];
$image = $row['post_image'];
?>
The error produced is: Fatal error: Cannot use object of type mysqli as array
The error is being called out on this line:
$run = mysqli_query($conn["___mysqli_ston"], $query);
In the line above $conn is a variable from the database connect file which has this code:
<?php
// Stored the db login credentials in separate file.
require("db_info.php");
// Supressing automated warnings which could give out clues to database user name, etc.
mysqli_report(MYSQLI_REPORT_STRICT);
// Try to open a connection to a MySQL server and catch any failure with a controlled error message.
try {
$conn=mysqli_connect ('localhost', $username, $password) or die ("$dberror1");
} catch (Exception $e ) {
echo "$dberror1";
//echo "message: " . $e->message; // Not used for live production site.
exit;
}
// Try to Set the active MySQL databaseand catch any failure with a controlled error message.
try {
$db_selected = mysqli_select_db($conn, $database) or die ("$dberror2");
} catch (Exception $e ) {
echo "$dberror2";
//echo "message: " . $e->message; // Not used for live production site.
exit;
// We want to stop supressing automated warnings after the database connection is completed.
mysqli_report(MYSQLI_REPORT_OFF);
}
?>
This line
$run = mysqli_query($conn["___mysqli_ston"], $query);
should be
$run = mysqli_query($conn, $query);
If you're migrating to mysqli, you should really read these docs at least.
The proper way to use a mysqli connection:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}
?>
you should also consider utilizing mysqli's prepared statements

sql queries embeded in php code don't get executed while working with cpanel

I am new at cpanel and I encountered a problem. I have made a database and a database user for it in cpanel and successfully connected to them via my php code. In spite of that I have a successful connection to database but none of my queries run in the application code (while they run in the phpMyadmin!).
<?php
session_start();
$conn =new mysqli('localhost','myDBname','myDBpass','myDBuser');
if($conn)
echo "<script>alert('successful connection');</script>";
$rawresults ="SELECT * FROM `articles`";
$result = $conn->query($rawresults);
if($result->num_rows>0)
{
echo "<script>alert('dd')</script>";
$_SESSION["i"]=0;
while($results = $result->fetch_assoc())
{
setcookie("searchResult","yes");
$_SESSION["topic".$_SESSION["i"]]=$results['topic'];
$_SESSION["name".$_SESSION["i"]]=$results['fileName'];
$_SESSION["texts".$_SESSION["i"]]=$results['texts'];
$_SESSION["i"]++;
}
header('location:index.php');
}
else if($result->num_rows==0)
{
echo "<script>alert('cc')</script>";
setcookie("searchResult","yes");
header('location:index.php');
}
?>
The problem is that I permanently face: alert(cc)! While table 'articles'
contains lots of information and num_rows is a positive value.
I 'd like to mention again that connection to db has no problem and I get alert(successful connection).
Try this after connecting:
if ($conn->connect_error) {
die('Connect Error (' . $conn ->connect_errno . ') '
. $conn->connect_error);
}

Querying a database with oop

I have connected to a database for the first time with oop and stright away come up with an issue, below is my code which i'm struggling with:
$q = 'SELECT * FROM test';
$sqli->query($q);
if($sqli->query($q)){
echo "worked";
}
if($sqli->error){
echo $sqli->error;
}
I have checked for errors when connecting to the db and that works fine, but when I run this query I get no output, why? I expected an error or "worked", but have got neither.
Whats happening?
I have put some comments in the source code to help:
$q = 'SELECT * FROM test';
//$sqli is the result of a
//new mysqli("localhost", "user", "password", "database");
$resource = $sqli->query($q); // this returns a resource or false
if(!$resource) {
echo $sqli->error;
die; // do not process further
}
// process the results
$rows = $resource->fetch_all();
if ($rows) { // check if there are rows
echo "worked";
}
else {
echo "query is ok, but there are no rows";
}
You could also use $resource->fetch_object() which returns an object for output. Therefore if you wanted to print specific data from the result set, you would do something like
//table test.Name and test.Country
while ($rowobj = $resource->fetch_object()){
printf ("%s (%s)\n", $rowobj->Name, $rowobj->Country);
}
Good luck,
You could use this method, I hope it's what you are looking for. You will need to define the DB first. Then you can connect in OOP and test the connection is true or exit();
Let me know if this works for you. You can also define the DB in an external file and just do an include(); towards the top of your script for any pages needing connection to the DB.
define("SERVER","IP Address");
define("USER","DB USERNAME");
define("PASSWORD","DB PASSWORD");
define("DATABASE","DB NAME");
// This is for connection
$mysqli = new mysqli(SERVER, USER, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit();
}

Categories