This code connects to a first database, loops and picks up a field called 'id' and use the id as a connection[database name] to another database in a function. All seemed to work except that in the function, the value of id does not change so cannot connect to db, even though it changes in the local variable. I suspect i need to unsett and set. Any help? Thanks
<?
$dbhost = "***";
$dbname = "users";
$dbuser = "****";
$dbpass = "***";
function myRecordHandler($record)
{
global $dbhost;
global $dbuser;
global $dbpass;
global $id;
global $conn2;
$db = mysql_select_db($id,$conn2) ;
$quantity = $record["QUANTITY"];
$price = $record["PRICE"];
$mytotal ="INSERT into `mytotal`(`quantity`,`price`) VALUES ($quantity,$price)";
mysql_query($mytotal,$conn2);
}
$conn1 = mysql_connect($dbhost, $dbuser, $dbpass, TRUE) or die("MySQL Error: " .mysql_error());
$conn2 = mysql_connect($dbhost, $dbuser, $dbpass, TRUE) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname,$conn1) or die("MySQL Error: " . mysql_error());
$query = "SELECT id,url FROM table userdata";
$result = mysql_query($query,$conn1);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$id =$row['id'];
$url=$row['url'];
MagicParser_parse($url,"myRecordHandler","xml|PRODUCTS/PRODUCT/");
}
?>
I suspect the problem is that myRecordHandler() is being called from within MagicParser_parse(). It's probably being called within a separate execution context that doesn't share the same global name space. This is just a hunch based on the fact that you're passing in "myRecordHandler" as a string.
Related
<?php
getdata();
function getdata(){
$server="";
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server;
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
?>
This bit makes no sense to me:
function getdata(){
$server=""; //<---------- set here
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server; //<---- sure you want to do this
//your basically setting $row[1] = '' on every iteration
//so your command below is "nslookup " because $server = ''
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
It seems to me this bit $row[1]= $server; is backwards.
But lets not forget the SQLInjection issues here:
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
Specifically this stuff:
function updatenslookup($url,$nsresult) {
// ....
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
// ....
}
The big issue with it is I can inject whatever I want into this table, then you take that data and shoot it right into
exec("nslookup ".$row[1], $result); //simplified $server = $row[1] + exec("nslookup ".$server)
So in theory I can (or may be able to) inject my own command line calls into exec, at least to some extent. I'm not sure all what someone could do with these issues, what the worst case would be, but I would avoid it in any case.
There is no way for me to know where the data for updatenslookup($url,$nsresult) comes from or if its clean, but it doesn't matter. One reason to prepare the sql is to have the security right where the issue is so you can clearly tell by looking at just the query if its safe or not. And you don't have to worry about missing some piece of data that could sneak in there.
You should use escapeshellarg at the very least, and clean up the SQL vulnerabilities by preparing your queries.
As far as this Call to a member function fetch_assoc() on array, I don't even see a call to fetch_assoc() in your code. Maybe I missed it but all I see is this $row = mysql_fetch_row($result); for reading data, which is procedural where you use the OOP in the other code . which is irritating .. but I get it, which is why I only use PDO now...
Etc..
I always feel bad when I shred up someones hard work, but I would be remiss not to mention such a big security hole.
Cheers.
I'm currently switching all the mysql_* functions to mysqli_* functions and i am getting the following errors .
PHP Warning: mysqli_connect(): (HY000/1040): Too many connections in
PHP Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in
PHP Warning: mysqli_error() expects parameter 1 to be mysqli, boolean
In config.php :
$dbuser = "xxx";
$dbpass = "xxx";
$dbhost = "xxxx";
$dbname = "xxxxxx";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass) or die("could not connect to mysql");
if($connection){
echo "\n Database connected ....\n\n";
}
mysqli_select_db($connection,$dbname) or die(mysqli_error($connection));
In other.php
require_once 'Lib/config.php';
class Mutex {
protected $connection;
public function __construct()
{
global $dbuser,$dbpass,$dbname,$dbhost; // globally declaring the config variables
$this->connection = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
//you need to exit the script, if there is an error
exit();
}
}
public function Prog($pack = null) {
if(isset($pack) && $pack != "") {
$sql_qry = "SELECT id from xxxx WHERE package like '" . addslashes($pack) . "'";
showSqlQuery($sql_qry);
$result = mysqli_query($this->connection,$sql_qry)or die(mysqli_error($this->connection));
if($result && mysqli_num_rows($result)>0) {
$row = mysqli_fetch_assoc($result);
if(!empty($row)) {
return "Exists";
}
}
return "NotExists";
}
return "InvalidProcess";
}
}
Tried many solutions, but none of them worked for me
Getting errors as shown above.
Please help me to solve this..
Thanks in advance.
I think your DB configuration has some issue.
Replace the following code of config.php file to bellow.
$dbuser = "xxx";
$dbpass = "xxx";
$dbhost = "xxxx";
$dbname = "xxxxxx";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Rather than duplicating ( nearly ) the connection you could try the approach where you pass a reference to the db connection as a parameter to the Mutex constructor
<?php
/* lib/config.php */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpass, $dbname );
?>
<?php
include 'lib/config.php';
class Mutex{
private $connection;
public function __construct( $dbo=object ){
$this->connection=$dbo;
}
public function Prog($pack = null) {
$result='InvalidProcess';
if( !empty( $pack ) ) {
$sql='select `id` from `xxxx` where `package` like ?';
$stmt=$this->connection->prepare( $sql );
if( $stmt ){
$var = '%'.$pack.'%';
$stmt->bind_param('s', $var );
$result=$stmt->execute();
if( $result && $stmt->num_rows > 0 ){
$stmt->store_result();
$stmt->bind_result( $id );
while( $stmt->fetch() ){/* do stuff perhaps */
echo $id;
}
$stmt->free_result();
$stmt->close();
$result='Exists';
}
}
}
return $result;
}
$pack='banana';
$mutex=new Mutex( $db );
$mutex->Prog( $pack );
?>
i am trying to run the following piece of SQL code in a php file
Select show_id, show_name
From (tv_shows JOIN distributes on D_SHOW_ID=SHOW_ID)
Where show_name= ‘Show Name’
(where 'Show Name' is a variable the the user passes in.) The SQL functions perfectly in mySQL but i just can't seem to print the results without errors occurring.
i tried
$mysqli = include ('./DBconnect.php');
$sql = 'SELECT show_id, show_name
FROM (tv_shows JOIN distributes ON D_SHOW_ID=SHOW_ID)
WHERE show_name= ? ';
$stmt = $mysqli-> prepare($sql);
// getting the variable from the user input
$showName = $_GET["name"];
//testing if the variable is passed through
echo $showName."is printed";
$stmt->bind_param('s',$showName);
$stmt-> execute();
$stmt -> bind_result($show_id,$show_name);
if ($stmt->fetch())
{
echo '<p> Show ID: '.$show_id.' Show Name'. $show_name.'</p><br>';
}
and it is giving me a "Call to a member function prepare() on null " error
i have a second php file that is called DBconnect.php which also seem to function correctly.
function get_mysqli_conn(){
$dbhost = "xxxxx";
$dbuser = "xxxxx";
$dbpassword = "xxxxx";
$dbname = "xxxxxx";
$conn = new mysqli($dbhost, $dbuser,$dbpassword,$dbname);
if (!$conn){
die ('Failed to connec to MySQL : (' . $conn->connect_errno.')' . $conn ->connect_error);
}else{
echo 'connected';
}
}
1st : you need to use connection object .
$stmt = $mysqli-> prepare($sql);
change to
$stmt = $conn-> prepare($sql);
2nd : you just need to include it like below .
$mysqli = include ('./DBconnect.php');
change to
include ('./DBconnect.php');
3rd : your connection creation is inside the function so you need to call the function once and get the connection object like below .
include ('./DBconnect.php');
$conn = get_mysqli_conn();
4th : In that function you need to return the connection object like below .
function get_mysqli_conn(){
$dbhost = "xxxxx";
$dbuser = "xxxxx";
$dbpassword = "xxxxx";
$dbname = "xxxxxx";
$conn = new mysqli($dbhost, $dbuser,$dbpassword,$dbname);
if (!$conn){
die ('Failed to connec to MySQL : (' . $conn->connect_errno.')' . $conn ->connect_error);
}else{
return $conn;
}
}
I want to be able to display document name and expiry date in order of expiry date in my browser. Mysql table name is employee_doc and the database name is employee_info. Here is my code
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'employee_info';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn ) {
die('Could not connect: ' . $mysqli->connect_error());
}
$mysqli = 'SELECT * FROM `employee_doc` ORDER BY `employee_doc`.`PPExp` ASC';
mysqli_connect($conn,"employee_info");
$retval = mysqli_query($conn,$mysqli);
if(! $retval ) {
die('Could not get data: ' . $mysqli->connect_error());
}
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
echo $row['PPNO'];
echo "<br>";
echo $row['PPExp'];
echo "<br>";
}
mysqli_close($conn);
?>
PPExp and PPNO are the column headings for expiry date and document name respectively. I am using Xampp. When I open the file from localhost die('Could not get data: ' . mysql_error()); is executed. What am I doing wrong?
You need to include the database name in your mysql connection.
Your code:
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
Revised Code:
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, "employee_info");
mysqli_connect: Open a new connection to the MySQL server.
mysqli_select_db: Selects the default database to be used when
performing queries against the database connection. This function
should only be used to change the default database for the connection.
This explains the basic concepts of both the functions.
Check mysqli_connect and mysqli_select_db for detailed explanation.
Change your code as follows:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'employee_info';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn )
{
die('Could not connect: ' . mysqli_connect_error());
}
$sql = 'SELECT * FROM `employee_doc` ORDER BY `employee_doc`.`PPExp` ASC';
$retval = mysqli_query($conn,$sql);
if(! $retval )
{
die('Could not get data: ' . mysqli_error($conn));
}
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC))
{
echo $row['PPNO'];
echo "<br>";
echo $row['PPExp'];
echo "<br>";
}
mysqli_close($conn);
?>
Also you are mixing mysql and mysqli
mysqli_select_db is use for changing current database to new database and using that for selecting database is not currect
You should select db in the process of mysqli_connect as others explained.
see: http://php.net/manual/en/mysqli.select-db.php
Provide database name:
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
and changes in
$retval = mysqli_query($conn,$sql);
and
while($row = mysqli_fetch_array($retval))
I'm having trouble with my DatabaseConnection class. I cannot seem to get $dbUser or $dbName variables to work for this connection class. I currently have to manually put the values in with quotes. Is there something I am doing wrong?
class DatabaseConnection {
private $dbHost = "localhost";
private $dbUser = "root";
private $dbPass = "";
private $dbName = "test";
function __construct() {
$connection = mysql_connect($dbHost, "root", $dbPass)
or die("Could not connect to the database:<br />" . mysql_error());
mysql_select_db("test", $connection)
or die("Database error:<br />" . mysql_error());
}
}
If you have suggestions for improving my current class, by all means, let me know!
Since this is a class, you have to access your class variables using $this->dbHost, $this->dbUser, etc instead of $dbHost, $dbUser. Php requires that you use $this->variableName for class variables.
EDIT:
Here's your code with the mysql_connect variables changed to access your class variables
class DatabaseConnection {
private $dbHost = "localhost";
private $dbUser = "root";
private $dbPass = "";
private $dbName = "test";
function __construct() {
$connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass)
or die("Could not connect to the database:<br />" . mysql_error());
mysql_select_db("test", $connection)
or die("Database error:<br />" . mysql_error());
}
}