I am writting a php file to get all users in mysql database printed. My problem is that after prepare($sql) and $statement->execute, statement is always null. Here is my code:
public function selectAllUser(){
$response = array();
$sql = "SELECT * FROM Tata.users";
$statement = $this->conn->prepare($sql);
if(!$statement){
throw new Exception($statement->error);
}
//echo json_encode($statement);
$statement->execute();
try {
throw new Exception($statement->error);
} catch (Exception $e){}
$result = $statement->get_result();
//echo json_encode($result);
while ($row = $result->fetch_assoc()){
//echo json_encode($row);
$response[] = $row;
}
return $response;
}
This is the result I get if I do: echo $statement;
{"affected_rows":null,"insert_id":null,"num_rows":null,"param_count":null,"field_count":null,"errno":null,"error":null,"error_list":null,"sqlstate":null,"id":null}
This is the code where I am using this function:
$file = parse_ini_file("../../../Tata.ini");
$dbhost = trim($file["dbhost"]);
$dbuser = trim($file["dbuser"]);
$dbpass = trim($file["dbpassword"]);
$dbname = trim($file["dbname"]);
require ("secure/access.php");
$access = new access($dbhost,$dbuser,$dbpass,$dbname);
$access->connect();
$users = $access->selectAllUser();
$access->disconnect();
echo json_encode($users);
Related
I'm trying to insert Blob images retrieved from MySQL into an array using a while loop.
The database statement selected all images then i need to pass them all into an array.
So in theory, i should have an array of base64 encoded image corresponding to each record from my database.
Any help will be appreciated.
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
//$result = base64_encode(); ---- Something here im guessing
$data[] = $result;
}
print_r ($data);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
I see big issue i your code..
You use the same variable, $result, for fetching mysql row result and image content.
Second, you miss to encoding to base64 the file content.
Here is my solution:
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
$data[] = base64_encode($result['img']);
}
print_r ($data);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
Hope it will helps you.
So the answer to this question came from AbraCadaver.
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
$data[] = base64_encode($result->img);
}
Thanks guys for the help!
can you help out a beginner trying to learn PHP? I wrote a code for changing password without any validations yet, just to change it and it does not work. It's been days I've been trying and couldn't figure out what's wrong. Thanks in advance.
id is variable name in database where id is kept.
db connection is done with first line and it definitely works.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
print_r($_SESSION);
function changePSW()
{
//$password = $_POST['currPassword']; // required
$newPassword = $_POST['newPassword']; // required
//$newPassword2 = $_POST['NewPassword2']; // required
$newPasswordH = password_hash($newPassword, PASSWORD_DEFAULT);
echo($newPassword);
$id = $_SESSION['userID'];
echo($id);
// create PDO connection object
$dbConn = new DatabaseConnection();
$pdo = $dbConn->getConnection();
try {
$statement = $pdo->prepare("SELECT * FROM `users` WHERE id = :id LIMIT 1");
$statement->bindParam(':id', $id);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
echo "SADASDASD";
// no user matching the email
if (empty($result)) {
$_SESSION['error_message'] = 'Couldnt find user';
header('Location: /Online-store/userForm.php');
return;
}
$sql = "UPDATE users SET password=:newPasswordH WHERE id = :id";
// Prepare statement
$stmt = $pdo->prepare($sql);
echo "AFGHANIKO";
// execute the query
$update_status = $stmt->execute(array(':password' => $newPasswordH, ':id' => $id));
echo "IHAAA";
echo($update_status);
if ($update_status === TRUE) {
echo("Record updated successfully" . "\r\n");
echo nl2br("\nPassword: ");
echo ($newPassword);
echo nl2br("\nHashed Password: ");
echo ($newPasswordH);
return true;
} else {
echo "Error updating record";
die();
}
} catch (PDOException $e) {
// usually this error is logged in application log and we should return an error message that's meaninful to user
return $e->getMessage();
}
}
if($_SESSION['isLoggedIn'] == true) {
require_once("database/DatabaseConnection.php");
unset($_SESSION['success_message']);
unset($_SESSION['error_message']);
changePSW();
}
?>
$update_status = $stmt->execute(array(':newPasswordH' => $newPasswordH, ':id' => $id));
This is what I needed to have instead of
$update_status = $stmt->execute(array(':password' => $newPasswordH, ':id' => $id));
I make users online page using PHP - OOP - PDO
include_once '../database.php';
$db = new database();
$getRows = $db->getRows('select * from visitors_online');
$gr = $db->rowCount();
$online = '';
$getRow = $db->getRow('select * from user_online');
$gr2 = $db->rowCount();
if(!empty($gr2)) {
try {
while ($getR = $getRow){
$getRow = $db->getRow('select * from users where id = ?',[$getR['session']]);
echo ',   '.$getRow['username'].'   ';
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
$total = $gr + $gr2;
The problems is:
* Not show any users except Admin, also I got this :
ONLINE
admin
Notice: Undefined index: session in /Applications/MAMP/htdocs/baws/admin/online.php on line 56
,
.Users = 0 ,Member = 2 , Register = 2
Who is online list
Here is the function from Database class
// Get row by id, username, or email etc..
public function getRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return $this->stmt->fetch();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
Any Help
Thanks
I tried to simplify a bit your code as I do not know your class details and it s messy.
The problem is you are not binding stuff properly neither fetching them properly too. Also, you are preparing the second query, each time you loop inside the query 1 results , that is useless. prepare both (withyour class or not) and just bind and execute.
$stmt1 = $db->prepare('select * from user_online where id= ?');
$result1 = getRows($stmt1, "1");
$gr1 = $db->rowCount();
if (!empty($gr1)) {
$stmt2 = $db->prepare('select * from users where id = ?');
foreach ($result1 as $key1 => $h1) {
$stmt2->bindParam(1, $h1['session'], PDO::PARAM_INT);
$stmt2->execute();
$result2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
if (count($result2) !== 0) {
foreach ($result2 as $key2 => $r2) {
echo ',   ' . $r2['username'] . '   ';
}
}
}
}
function getRow($query, $para) {
$stmt1->bindParam(1, $para, PDO::PARAM_INT);
try {
$stmt1->execute($para);
$result1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
return $result1;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
Please find the database class here
class database {
public $isConn;
protected $datab;
private $stmt;
public function __construct() {
$this->connect();
}
// connect to database
private function connect(){
$host = 'localhost';
$db = 'baws';
$user = 'root';
$pass = 'root';
$option = [];
$this->isConn = TRUE;
try {
$this->datab = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pass, $option);
$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo '<h3>Not connected</h3>' . $e->getMessage();
}
}
// Disconnected from database
private function disconnect(){
$this->isConn = NULL;
$this->datab = FALSE;
}
//insert to database
public function insertRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return TRUE;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
//update row to database
public function updateRow($query, $para = []){
$this->insertRow($query, $para);
}
//Delete row from database
public function deleteRow($query, $para = []){
$this->insertRow($query, $para);
}
// Get row by id, username, or email etc..
public function getRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return $this->stmt->fetch();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
}
online.php Page
ob_start();
echo "ONLINE <br>";
include_once '../database.php';
$db = new database();
try {
$session=$_COOKIE['id'];
$time=time();
$time_check=$time-300; //SET TIME 10 Minute
$getRow = $db->getRow("SELECT * FROM user_online WHERE session = ?", [$session]);
$count =$db->rowCount($getRow);
if($count == '0'){
$insertRow = $db->insertRow("INSERT INTO user_online(session, time)VALUES(? , ?)",[$session, $time ]);
}
elseif($count != '0'){
$updateRow = $db->updateRow("UPDATE user_online SET time = ? WHERE session = ?", [$time, $session]);
}else{
$deleteRow = $db->deleteRow("DELETE FROM user_online WHERE time < ? ", [$time_check]);
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
try {
$ip=$_SERVER['REMOTE_ADDR'];
$session=$ip;
$time=time();
$time_check=$time-300; //SET TIME 10 Minute
$deleteRow = $db->deleteRow("DELETE FROM visitors_online WHERE time < ? ", [$time_check]);
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
$getRows = $db->getRows('select * from visitors_online');
$gr = $db->rowCount();
$online = '';
$getRow = $db->getRow('select * from user_online');
$gr2 = $db->rowCount();
if(!empty($gr2)) {
try {
while ($getR = $getRow){
$getRow = $db->getRow('select * from users where id = ?',[$getR['session']]);
echo ',   '.$getRow['username'].'   ';
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
$total = $gr + $gr2;
} //end
I want to make a sendmail function on my program. But first, I want to store the information: send_to, subject, and message in a table in another database(mes) where automail is performed. The problem is data fetched from another database(pqap) are not being added on the table(email_queue) in database(mes).
In this code, I have a table where all databases in the server are stored. I made a query to select a specific database.
$sql5 = "SELECT pl.database, pl.name FROM product_line pl WHERE visible = 1 AND name='PQ AP'";
$dbh = db_connect("mes");
$stmt5 = $dbh->prepare($sql5);
$stmt5->execute();
$data = $stmt5->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
Then after selecting the database,it has a query for selecting the information in the table on the selected database. Here's the code.
foreach ($data as $row5) GenerateEmail($row5['database'], $row5['name']);
Then this is part (I think) is not working. I don't know what's the problem.
function GenerateEmail($database, $line) {
$sql6 = "SELECT * FROM invalid_invoice WHERE ID=:id6";
$dbh = db_connect($database);
$stmt6 = $dbh->prepare($sql6);
$stmt6->bindParam(':id6', $_POST['idtxt'], PDO::PARAM_INT);
$stmt6->execute();
$data = $stmt6->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
foreach ($data as $row6) {
$invnumb=$row6['Invoice_Number'];
$partnumb=$row6['Part_Number'];
$issue=$row6['Issues'];
$pic=$row6['PIC_Comments'];
$emailadd= $row6['PersoninCharge'];
if($row6['Status']=="Open") {
$message = "<html><b>Invoice Number: {$invnumb}.</b><br><br>";
$message .= "<b>Part Number:</b><br><xmp>{$partnumb}</xmp><br><br>";
$message .= "<b>Issues:</b><br><xmp>{$issue}</xmp><br>";
$message .= "<b>{$pic}<b><br>";
$message .= "</html>";
if(!empty($emailadd)) {
dbInsertEmailMessage($emailadd, "Invoice Number: {$invnumb} - {$issue}.", $message);
$dbh=null;
}
}
}
}
function dbInsertEmailMessage($send_to, $subject, $message) {
$sql7 = "INSERT INTO email_queue (Send_to, Subject, Message) VALUES (:send_to, :subject, :message)";
$dbh = db_connect("mes");
$stmt7 = $dbh->prepare($sql7);
$stmt7->bindParam(':send_to', $send_to, PDO::PARAM_STR);
$stmt7->bindParam(':subject', $subject, PDO::PARAM_STR);
$stmt7->bindParam(':message', $message, PDO::PARAM_STR);
$stmt7->execute();
$dbh=null;
}
Here's my db connection:
function db_connect($DATABASE) {
session_start();
// Connection data (server_address, database, username, password)
$servername = '*****';
//$namedb = '****';
$userdb = '*****';
$passdb = '*****';
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
$dbh = new PDO("mysql:host=$servername; dbname=$DATABASE", $userdb, $passdb, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
return $dbh;
//echo 'Connected to database';
}
catch(PDOException $e) {
echo $e->getMessage();
}
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
There are a couple things that may help with your failed inserts. See if this is what you are looking for, I have notated important points to consider:
<?php
// take session_start() out of your database connection function
// it draws an error when you call it more than once
session_start();
// Create a connection class
class DBConnect
{
public function connect($settings = false)
{
$host = (!empty($settings['host']))? $settings['host'] : false;
$username = (!empty($settings['username']))? $settings['username'] : false;
$password = (!empty($settings['password']))? $settings['password'] : false;
$database = (!empty($settings['database']))? $settings['database'] : false;
try {
$dbh = new PDO("mysql:host=$host; dbname=$database", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// You return the connection before it hits that setting
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
catch(PDOException $e) {
// Only return the error if an admin is logged in
// you may reveal too much about your database on failure
return false;
//echo $e->getMessage();
}
}
}
// Make a specific connection selector
// Put in your database credentials for all your connections
function use_db($database = false)
{
$con = new DBConnect();
if($database == 'mes')
return $con->connect(array("database"=>"db1","username"=>"u1","password"=>"p1","host"=>"localhost"));
else
return $con->connect(array("database"=>"db2","username"=>"u2","password"=>"p2","host"=>"localhost"));
}
// Create a query class to return selects
function query($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return (!empty($result))? $result:0;
}
// Create a write function that will write to database
function write($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
}
// Do not create connections in your function(s), rather pass them into the functions
// so you can use the same db in and out of functions
// Also do not null the connections out
function GenerateEmail($con,$conMes,$line = false)
{
if(empty($_POST['idtxt']) || (!empty($_POST['idtxt']) && !is_numeric($_POST['idtxt'])))
return false;
$data = query($con,"SELECT * FROM `invalid_invoice` WHERE `ID` = :0", array($_POST['idtxt']));
if($data == 0)
return false;
// Instead of creating a bunch of inserts, instead create an array
// to build multiple rows, then insert only once
$i = 0;
foreach ($data as $row) {
$invnumb = $row['Invoice_Number'];
$partnumb = $row['Part_Number'];
$issue = $row['Issues'];
$pic = $row['PIC_Comments'];
$emailadd = $row['PersoninCharge'];
if($row['Status']=="Open") {
ob_start();
?><html>
<b>Invoice Number: <?php echo $invnumb;?></b><br><br>
<b>Part Number:</b><br><xmp><?php echo $partnumb; ?></xmp><br><br>
<b>Issues:</b><br><xmp><?php echo $issue; ?></xmp><br>
<b><?php echo $pic; ?><b><br>
</html>
<?php
$message = ob_get_contents();
ob_end_clean();
if(!empty($emailadd)) {
$bind["{$i}to"] = $emailadd;
$bind["{$i}subj"] = "Invoice Number: {$invnumb} - {$issue}.";
$bind["{$i}msg"] = htmlspecialchars($message,ENT_QUOTES);
$sql[] = "(:{$i}to, :{$i}subj, :{$i}msg)";
}
}
$i++;
}
if(!empty($sql))
return dbInsertEmailMessage($conMes,$sql,$bind);
return false;
}
function dbInsertEmailMessage($con,$sql_array,$bind)
{
if(!is_array($sql_array))
return false;
write($con,"INSERT INTO `email_queue` (`Send_to`, `Subject`, `Message`) VALUES ".implode(", ",$sql_array),$bind);
return true;
}
// Create connections
$con = use_db();
$conMes = use_db('mes');
GenerateEmail($con,$conMes);
I am working on an app that needs to select data from a MySQL database. I am currently testing the PHP script via my browser to make sure that it is returning the correct data. The issue is currently it returns the exception "Database Error!". I have included my PHP script.
get_agencies_by_city.php
<?php
/*
* Following code will get all agencies matching the query
* Returns essential details
* An agency is identified by agency id
*/
require("DB_Link.php");
$city = ($_GET['City']);
//query database for matching agency
$query = "SELECT * FROM agency WHERE City = $city";
//Execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
//Retrieve all found rows and add to array
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Agency found!";
die(json_encode($response));
}
?>
Here is the DB_Link.php
<?php
// These variables define the connection information the MySQL database
// set connection...
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
You should rewrite your query to this, as it is a prepared statement and your query will be much safer (and working)!
//your code
try {
$statement = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$statement->execute(array('city' => $city));
// rest of your code
}
// and the exception
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
also you should check if $_GET really is set!
LIKE THIS:
try {
$stmt = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$stmt->execute(array('city' => $city));
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} }
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
The variable $city needs to be in your query. Do something like this:
$query = "SELECT * FROM Agency WHERE City = " . $city;