How do I make a query using PDO? - php

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);
}

Related

How to select all table names from a database and show them in select option(or dropdown) in php and msqli [duplicate]

I have looked around and still can't find how to list all my tables in a database. is it possible with MySQLi?
Thanks.
There are many ways.
SHOW TABLES
Is the most simple SQL statement for doing that. You can also take a look at INFORMATION_SCHEMA.TABLES if you want to have more details or do some filtering or such.
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA LIKE 'your_database';
Using PHP 5.5 or later, a simple solution is using PHP's built-in array_column() function.
$link = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);
$listdbtables = array_column($link->query('SHOW TABLES')->fetch_all(),0);
I'd try something like:
function get_tables()
{
$tableList = array();
$res = mysqli_query($this->conn,"SHOW TABLES");
while($cRow = mysqli_fetch_array($res))
{
$tableList[] = $cRow[0];
}
return $tableList;
}
$link = mysqli_connect("localhost", "domain_root", "##pwd", "domain_DBname");
$query = mysqli_query($link, "SHOW TABLES IN domain_DBname");
$numrows = mysqli_num_rows($query);
echo "<b>Amount of tables: ".$numrows." and their names:</b>";
while ($row = mysqli_fetch_array($query)) {
echo $row[0]." ";
}
here is little example
class database {
public $connection;
function __construct() {
$this->connection = mysqli_connect(DBHOST,
DBUSER,
DBPASS,
DBNAME) or
die('Database Connection Error: '.mysqli_connect_error());
}
public function close_database() {
return mysqli_close($this->connection);
}
public function query($query) {
$query = mysqli_query($this->connection ,$query) or die($this->show_errors('Query Execution Error: '.mysqli_error($this->connection),'E'));
return $query;
}
public function fetch_assoc($query) {
$query = mysqli_fetch_assoc($query);
return $query;
}
}
$db = new database();
$query = $db->query("SHOW TABLES FROM DATABASENAME");
$db->fetch_assoc($query);

how to make a query with database as a variable

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.

How to make this live validation work with my sql PDO

my intention is to make a live validation , which i found a side that tutorial but they are using old sql , i wanted to use my sql PDO , but i cant make it work , even my database having the same name , it still say ok.
how do i make it work , before you check my code , please look and download the link to check it out, thank.
download from here:
Please Check This Link
my code(i changed some to PDO but still wont work)
dbConnector.php
<?php
class DbConnector {
var $link;
function DbConnector(){
try{
$this->link = new PDO('mysql:host=127.0.0.1;dbname=system', 'root', '123456');
$this->link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->link->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
}catch(PDOException $e){
die("this is not connected");
}
}
//*** Function: query, Purpose: Execute a database query ***
function query($query) {
try{
$this->link->prepare($query);
}catch(PDOException $e){
die("fail to prepare");
}
return $this->link;
}
}
?>
check.php
<?php
include("dbConnector.php");
$connector = new DbConnector();
$username = trim(strtolower($_POST['username']));
$query = "SELECT air_users FROM USER_NAME WHERE username = ? LIMIT 1";
$result = $connector->query($query);
$result->execute(array($username));
$num = $result->rowCount();
$num = $result->fetch();
echo $num;
// mysql_close();
?>
i dont have any error , but still it wont work. thank for helping out.
You need to return the returned value of $this->link->prepare($query); not the $this->link itself. To make it work, rewrite your query this way:
function query($query) {
return $this->link->prepare($query);
}
I don't think that the $username variable is been interpreted on the string, as you have it.
"SELECT users FROM USER_NAME WHERE username = :username' LIMIT 1";
...
execute(array(':username' => $username));
and on the query method call prepeare like:
$this->link->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
or
"SELECT users FROM USER_NAME WHERE username = ? LIMIT 1";
...
execute(array($username));
And the prepare method should be call like you have it on your example:
$this->link->prepare($query);
And on the query method you return the $query or the string. You should return the instance or execute in the query method.
function query($query) {
try{
$this->link->prepare($query);
}catch(PDOException $e){
die("fail to prepare");
}
return $this->link;
}
See

How to wite PHP code with the following SQL query?

I am trying to query out a result, it works in SQL query, but I'm trying to get the result using PHP
SELECT prs_amtdb FROM `prs` WHERE prs_amtcrck = 0
Using mysqli
Note: Make sure you bind your value. mysqli does not automatically
secure your query
$connection= mysqli_connect($host, $user, $password, $database);
$query="SELECT prs_amtdb FROM prs WHERE prs_amtcrck = 0";
$result= mysqli_query($connection, $query);//$connection is your database
//connection
//fetch the result
while($row= mysqli_fetch_array($result)){
echo $row['column_name'].'<br/>';
}
Using PDO:
$query = $db->query("SELECT `prs_amtdb` FROM prs WHERE `prs_amtcrck` = 0");
$results = $query->fetchAll();
foreach($results as $result) {
echo $result;
}
http://php.net/manual/en/pdo.query.php
If you have user input that you're using in your query you should always use prepared statements eg:
$query = $db->prepare("SELECT `prs_amtdb` FROM prs WHERE `prs_amtcrck` = :atmcrck");
$query->bindParam(':atmcrck', 0); // 0 will be the user input
$query->execute();
$results = $query->fetchAll();
foreach($results as $result) {
echo $result;
}
Make sure you have a database connection setup in PDO:
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
die($e->getMessage());
}
http://php.net/manual/en/pdo.connections.php

I'm a little confused, PHP says $results is a non-object of the mysqli class

I'm trying to fetch results using mysqli->fetch_row() (or fetch_object(), fetch_array()), yet when I go to run the code at run time it gives me the following error:
Fatal error: Call to a member function fetch_row() on a non-object in...on line 23.
The var in question that does this is $results in the code below. $user and $password gain their values from another .php file that this file is being included in so that's not really important at the moment. Now correct me if I'm wrong but if $results is being set = to $db->query($query) then isn't it supposed to inherit the properties of $db aka the mysqli class?
class mySQLHelper{
public function checkPass($user, $pass){
global $db;
$db = new mysqli();
$db->connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()){
echo 'Can not connect to database';
echo mysqli_connect_errno(). mysqli_connect_error();
exit;
return false;
}
$query = "SELECT user, password FROM Users WHERE user = $user AND password = $pass " ;
echo $query;
$results = $db->query($query);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
$results->close();
$url = 'http://'. $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
if(!$results){
// mysqli_close($db);
// header("Location:.$url.login.php&msg=1");
}
else{
// mysqli_close($db);
// header("Location:.$url.featured.php");
}
}
}
Your query is failing on this line:
$results = $db->query($query);
Because of this, $results is false - not a result object as you expect.
To fix the issue, you need to add quotes around your variables (or use prepared statements):
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
I would suggest updating to use a prepared statement to prevent SQL-injection issues too though:
$stmt = $db->prepare('SELECT user, password FROM Users WHERE user = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$results = $stmt->get_result();
You script is lacking error checking, and therefore the error in the query is not handled.
$query = "SELECT user, password FROM Users
WHERE user = '$user' AND password = '$pass' " ;
// ^ quotes needed
echo $query;
$results = $db->query($query);
// handle a error in the query
if(!$results)
die($db->error);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
If you user & password field text or varchar, then you need to use single quote around them
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
You have to check, if query runs properly:
if ($result = $mysqli->query($query))
{
}
Use: var_dump($results) to check what it contains
Why are you checking if($results) after trying to manipulate it?
This...
$results->close();
//...
if(!$results){
//...
}
Should be...
if(!$results){
//...
}
$results->close();

Categories