how to make a query with database as a variable - php

I have two databases - lorem and nts.lorem - and need to operate with both of them
$user = 'root';
$pass = '';
$db1 = new PDO('mysql:host=localhost; dbname=nts.lorem', $user, $pass);
$db2 = new PDO('mysql:host=localhost; dbname=lorem', $user, $pass);
everything works fine until db is a variable in an ajax request - for example:
js
var db;
if(something is true){db = 'db1';};
else{db = 'db2';}
//... ajax post code
php
function something($db){
global $db1, $db2;
// how to say the next line
$sq = "select id from " . $db . ".tableName order by title asc";
// error - table db1.tableName doesn't exist
}
any help?

Choose connection according to $db value:
function something($db){
global $db1, $db2;
$sq = "select id from tableName order by title asc";
if ($db === 'db1') {
$db1->execute($sq);
} else {
$db2->execute($sq);
}
// rest of the code
}

Add the line that executes the query to your code sample. Without it, it's hard to be sure what's wrong, but I can guess: you don't need the name of the database in the query text, you need to execute the query with the proper database connection, based on the parmeter received from the client.
Something like:
function something($db){
global $db1, $db2;
$sq = "select id from tableName order by title asc";
$stmt = $db === 'db1' ? $db1->query($sq) : $db2->query($sq);
$result = $stmt->fetch();
}
Comment: this assumes you have a table called tableName in both databases.

Related

Php webservice looping

I am about to lose my mind.I dont have any php experince and I am struggling about php web service.
Here is my code;
<?php
private $username2 = "";
private $password2 = "";
private $DB_CONNECTION;
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "dptest";
function __construct()
{
$this->DB_CONNECTION = mysqli_connect($this->servername, $this->username,
$this->password, $this->dbname);
}
function getUserType(){
$sql = "SELECT usertype FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
$result = mysqli_query($this->DB_CONNECTION,$sql);
//$value = mysqli_fetch_array($result);
while(!is_null($value = mysqli_fetch_array($result))){
return $value['usertype'];
}
}
}
This is my function code.The other is my login code;
<?php
include_once 'Authentication.php';
use user\Authentication;
$auth = new Authentication();
$auth->prepare($_POST);
$userStatus = $auth->isUserValidToLogIn();
if ($userStatus) {
// user existed
// So log him to main page
$json['success'] = 1;
$json['message'] = 'access granted';
$json['usertype'] = $auth->getUserType();
echo json_encode($json);
} else {
$json['success'] = 0;
$json['message'] = 'error!';
echo json_encode($json);
}
I am trying to get the user's type but when try to get the data form phpmyadmin local database it only gives the first column's usertype.When I try to get 2nd,3rd,4th so on.. user's usertype it doesnt return anything and blank page shows up on postman app.
Also my database looks like this;
usertype username password
admin despro 1234
client test 1234
client despro2 1234
client despro3 1234
The reason you are only getting one column back is because you only request the one column. In order to get the columns you want you need to explicitly request them in your query or use '*' in order to get all columns back. So your query should look like this in order to get all columns from the data table:
$sql = "SELECT * FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
In general, I highly recommend that you stop using MySQLi extension and start using PHP Data Objects (PDO). It makes it easy to use prepared statements. Which also makes your code safer.
Then your query could look something like this (this is NOT the complete code):
// connecting to db
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT *
FROM login_test
WHERE userName = :username
AND pass = :password;';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username2, PDO::PARAM_STR);
$stmt->bindParam(':password', $password2, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
$response["userdata"] = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
}
Note that the code above is for returning multiple rows of data. If you just want the one row then use something like this:
if ($res) {
$response["userdata"] = array();
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
removing the 'while' statement.
You might want to take a look at this answer I gave, recently. It is a comprehensive example of using a webservice from an Android app.
How to insert all the SQL table data into an array in java [android studio]

PHP MySQL Query Where x = $variable from function

Why is this not working:
function listOrderComments ($factnr){
global $connection;
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
When I echo $factnr I get "123" back.
When I uncommented //$factnr = 123; my function is working.
Looked everywhere for a solution. check the type $factnr is (string).
Well if you're using a variable in your query you're opening yourself up to an injection attack for one.
If you're going to be using that variable I would recommend you use bind_param for your query
Read the PHP manual link below and you will be able to figure out the issue
http://php.net/manual/en/mysqli-stmt.bind-param.php
If you're passing in a variable to your function it should already be set so I don't understand why you're setting it to 123 anyway. So execute the sql statement and bind the parameter following the first example on the PHP docs page.
public function listOrderComments ($factnr)
{
global $connection;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ?";
$sql->prepare($query);
$sql->bind_param("s", $factnr);
$sql->execute();
$result = $sql->get_result();
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($data as $row) {
print_r($row);
}
}
Then do what you want with the result
You can go with:
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ". $factnr;
Concatenating your code is not good practise. Your best solution is to use PDO statements. It means that your code is easier to look at and this prevents SQL injection from occuring if malice code slipped through your validation.
Here is an example of the code you would use.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$factnr = "123" // or where-ever you get your input from.
$query = "SELECT * FROM orderstatus WHERE factuurnummer = :factnr";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("factnr" => $factnr);
$statement->execute($statementInputs);
//Returns results as an associative array.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
//Shows array of results.
print_r($result);
?>
Use it correctly over "doted" concat. Following will just work fine:
$factnr = 123;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
UPDATE:
here is $factnr is passing as argument that supposed to be integer. Safe code way is DO NOT use havvy functions even going over more complicated PDO, but just verify, is this variable integer or not before any operation with it, and return some error code by function if not integer. Here is no danger of code injection into SQL query then.
function listOrderComments ($factnr){
global $connection;
if (!is_int($factnr)) return -1
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
$result = mysqli_query($connection, $query);

How select from one MYSQL DB and insert it into another?

I'm running some small Updates via CRON and execute them with PHP.
Now I want to select something from DB1 and insert it into DB2
My Problem is, that these 2 DBs are on the same Server but with 2 different Users and its not possible to give 1 User permission to both DB's.
So I know this works with one user and dbconnect:
insert into db1.tbl1(data1,data2) values (select data2, data1 from db2.tbl2)
How can I do it with 2 db connects in one Loop?
Thanks
you can create two files of connection like this
<?PHP
function connect(){
$servername = "localhost";
$username = "user";
$password = "psw";
$database = "database";
$conn = new mysqli($servername, $username, $password, $database);
if(mysqli_connect_errno()){
echo "Error conectando a la base de datos: " . mysqli_connect_error();
exit();
}
else{
$conn->query("SET NAMES 'utf8'");
return $conn;
}
}
function disconnect($connection){
$disconnect = mysqli_close($connection);
}
?>
and in your php file and like this
require("connection.php");
$connection=connect();
require("connection2.php");
$connection2=connect2();
obviously in your connection2.php your funtion named connect2(); and in your loop you can use the two connection
$query="insert into db1.tbl1(data1,data2) values (select data2, data1 from db2.tbl2)";
$messageResult = "Good";
$band = true;
if(!($connection -> query($query))){
$messageResult = "Error";
$band = false;
}
or..
$query="insert into db1.tbl1(data1,data2) values (select data2, data1 from db2.tbl2)";
$messageResult = "Good";
$band = true;
if(!($connection2 -> query($query))){
$messageResult = "Error";
$band = false;
}
If u r using pdo. U declare 2 different connection.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass)
$dbh2 = new PDO('mysql:host=localhost;dbname=test', $user2, $pass)
Then u do this
$query = $dbh->prepare(select statement);
$query->execute();
$data = $query->fetchAll(); // you get array of data
$query = $dbh2->prepare(insert statement);
$query->execute()
Create 2 dB connection in two different variable and make that work .... Take value of first db in one variable and simply dump that variable into second db .... Or you can use another dB or caching dB like redis to store one time temporary base.

How to display the number of rows using the SQL query COUNT

When I run this query SELECT COUNT(ID) FROM blog_posts in PHPmyadmin it returns the number of rows in my database which is what I want but now I want this number to be displayed on my success.php page using the count method below.
Heres my code so far:
Database.class.php
<?php
include 'config/config.php'; // Inlude the config file, this is where the database login info is stored in an array
class database {
private $dbc; // Define a variable for the database connection, it's visabiliatly is set to 'private' so only this class can access it
function __construct($dbConnection){
// Running the __construct() magic function,
// I am passing through a variable into the contruct method which when the object is created will hold the login details from the $dsn array in config.php
$this->dbc = $dbConnection; // This is saying that the variable $dbc now has the same value as $dbConnection ($dsn array)
$this->dbc = mysqli_connect($this->dbc['host'], $this->dbc['username'], $this->dbc['password'], $this->dbc['database']);
// ^ Running the mysqli_connect function to connect to the database.
if(mysqli_connect_errno()){ // If there is a problem connecting it will throw and error
die("Database connection failed" . mysqli_connect_error());
} else {
echo "allgood";
}
}
function insert($insertSQL){ // Creating an insert function and passing the $insertSQL variable into it
mysqli_query($this->dbc, $insertSQL); // Querying the database and running the query that is located in 'success.php'.
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $insertSQL" . $this->dbc->error);
}
}
function count($countSQL){ // This is the method used for counting
mysqli_query($this->dbc, $countSQL);
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $countSQL" . $this->dbc->error);
}
}
}
?>
Success.php
<?php
include 'classes/database.class.php';
include 'config/config.php';
echo '<h2>Success page</h2>';
$objdb = new database($dsn);
$insertSQL = "INSERT INTO blog_posts VALUES(NULL, 'Test', 'THis is a message')";
$objdb->insert($insertSQL);
$countSQL = "SELECT COUNT(ID) FROM blog_posts";
$objdb->count($countSQL); // Executes the query, now how do I display the result? I have tried 'echo'ing this but it doesn't seem to work
?>
Actually its much better to add an alias in your query:
$countSQL = "SELECT COUNT(ID) as total FROM blog_posts";
$result = $objdb->count($countSQL);
echo $result['total'];
Then, on your methods:
function count($countSQL){ // This is the method used for counting
$query = mysqli_query($this->dbc, $countSQL);
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $countSQL" . $this->dbc->error);
}
$result = $query->fetch_assoc();
return $result;
}
Additional Info:
It might be good also on your other methods to put a return value. So that you'll know that it worked properly.
Example:
function insert($insertSQL){ // Creating an insert function and passing the $insertSQL variable into it
$query = mysqli_query($this->dbc, $insertSQL); // Querying the database and running the query that is located in 'success.php'.
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $insertSQL" . $this->dbc->error);
}
return $this->dbc->affected_rows;
}
So that here:
$insertSQL = "INSERT INTO blog_posts VALUES(NULL, 'Test', 'THis is a message')";
$insert = $objdb->insert($insertSQL); // so that its easy to test if it indeed inserted
if($insert > 0) {
// hooray! inserted!
}

How do I make a query using PDO?

I am trying to make this query using PDO and it is returning and error.I have already verified the connection to the database.
function temperaturaMedia($data_inicio,$data_final,$ema)
{
$db = 'sensorzapp_db';
$query = "SELECT
DATE(DTM) AS 'Dia',
ROUND(AVG(TMP),1) AS 'Temp. Med.'
FROM dados_meteo
WHERE POM = '$ema'
AND DATE(DTM) BETWEEN '$data_inicio' AND '$data_final'
GROUP BY DATE(DTM)";
$stmt = $db->query($query);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
You are trying to execute a query on a string, you need to connect to the database, like this:
function temperaturaMedia($data_inicio,$data_final,$ema)
{
try {
$db = new PDO("mysql:host=localhost;dbname=sensorzapp_db","user","password");
} catch($ex) { die("Connection failed"); } // To not disclosure username & password when connection fails (look at the red box on http://www.php.net/manual/de/pdo.connections.php)
$query = "SELECT
DATE(DTM) AS 'Dia',
ROUND(AVG(TMP),1) AS 'Temp. Med.'
FROM dados_meteo
WHERE POM = '$ema'
AND DATE(DTM) BETWEEN '$data_inicio' AND '$data_final'
GROUP BY DATE(DTM)";
$stmt = $db->query($query);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

Categories