wrong value from MYSQL using PHP - php

when running this query in phpMyAdmin, I get the correct values,
but when using the same line in a PHP script,
It always gives x=0 y=0.
All other values are correct only x and y
for some reason return 0.
EDITED not getting the right values
code:
$sql = "select a.image_id as id,
i.image_url as url,
i.image_x as x,
i.image_y as y
from album a
join images i
where a.album_id = 1
and
i.image_id = a.image_id";
echo getFunc($sql);
function getFunc($sql) {
try {
$db = getConnection();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$db = null;
return json_encode($result);
} catch(PDOException $e) {
echo $e->getMessage();
}
};
function getConnection() {
$dbhost="127.0.0.1";
$dbuser="root";
$dbpass="";
$dbname="efrattest";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec("set names utf8");
return $dbh;
}
mySQL table:
image_id int(11)
image_url varchar(250)
image_x int(9)
image_y int(9)

Thanks everybody,
the problem lays at
$dbhost="127.0.0.1";
I changed that from 'localhost' to '127.0.0.1'
as it was supposed to be better with PDO (A tip I heard online)
changed it back to 'localhost' now everything works as it should.

Related

PHP Cannot Fetch larger data from database

Function getUsers_Test() can retrieve data with the limit of 10 rows only while my getUsers_Orig() cannot retrieve any records **my record in the database is almost 50 rows*. No error, no warning. (PHP version 5.5.12)
function getUsers_Test(){
$sql = "SELECT TOP 10 a.user_name, a.user_level, a.user_status, b.* FROM user_access a, user_details b WHERE a.emp_code = b.emp_code ORDER BY a.id DESC";
try{
$data = array();
$db = null;
$db = connectDB();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
}catch(PDOException $e){
$data['message'] = "Error: " . $e;
}
echo json_encode($data);
}
function getUsers_Orig(){
$sql = "SELECT a.user_name, a.user_level, a.user_status, b.* FROM user_access a, user_details b WHERE a.emp_code = b.emp_code ORDER BY a.id DESC";
try{
$data = array();
$db = null;
$db = connectDB();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
}catch(PDOException $e){
$data['message'] = "Error: " . $e;
}
echo json_encode($data);
}
function connectDB() {
$dbuser = "myusername";
$dbpass = "mypassword";
$dbh = new PDO('odbc:databaseName', $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
You could try catching a general exception instead of the PDOException
try
{
// ...
} catch (\Exception $e) {
// ...
}
The size of data is not a problem here, the data I was fetching has a special character (A‘ for Ñ). I use to add charset UTF-8 in my connection but still, I wasn't able to fetch it.
This problem occurs when I perform Generate Script and extract data from MSSQL instead of Backup and Restore. So when I execute the script from the Generate Script feature of MSSQL, the character changed and I didn't notice it.

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.

Windows Azure MaxSizeInByte Statement

i want to get the current max size of my DB. I have found the statements an checked it out. It works fine in VS2012 SQL Explorer. But when im using php im geting no data.
This is my function:
function getLoad() {
$conn = connect();
$string = 'DATABASEPROPERTYEX ( 'database' , 'MaxSizeInBytes' )';
$stmt = $conn->query($string);
return $stmt->fetchAll(PDO::FETCH_NUM);
}
The problem is that i get an error in fetching the $stmt. Error is:
can not fetchAll(11)
This code will print the database edition and max size in GB:
<?php
function get_database_properties($server, $database, $username, $password) {
try {
$conn = new PDO ("sqlsrv:server=tcp:{$server}.database.windows.net,1433; Database={$database}", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$query = "SELECT CONVERT(NVARCHAR(128), DATABASEPROPERTYEX ('{$database}', 'Edition')) as 'Edition', " .
"CONVERT(DECIMAL,DATABASEPROPERTYEX ('{$database}', 'MaxSizeInBytes'))/1024/1024/1024 AS 'MaxSizeInGB'";
$stmt = $conn->query($query);
$row = $stmt->fetch();
$conn = null;
return $row;
}
catch (Exception $e) {
die(print_r($e));
}
}
$db_properties = get_database_properties("yourserver", "yourdatabase", "youruser", "yourpassword");
print("Edition={$db_properties['Edition']} MaxSizeInGB={$db_properties['MaxSizeInGB']}\n");
?>

Returning a single value using PDO MYSQL

I am crossing over to PDO and want to, simply put, return a single value from a table (and I feel really stupid for not getting it right). I am not getting any errors, but also no values, where there should be :)
try {
$sql = "SELECT `column_name` FROM `table` ORDER BY `id` DESC LIMIT 1";
$query = $this->handler->query($sql);
$result = $query->fetchColumn();
print_r($result);
}
catch(PDOException $e) {
return false;
}
return true;
Print the error message:
catch(PDOException $e) {
print_r($e->getMessage());
return false;
}
As shown this would work, if you have correctly connected to the database.
Check that your object is successfully connecting to the database, and that you have the correct column name and table name.
A snippet from one of my DB classes:
/**********************************************************************
* Try to connect to mySQL database
*/
public function connect($dbuser, $dbpassword, $dbhost ,$dbname)
{
try {
$this->dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpassword);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return true;
} catch (PDOException $e) {
$this->setError($e->getMessage());
}
}

Select data from database and update it PHP/PDO

I need to make a PHP code that gets data from server, updates it and echos that updated data to user. I am beginner with PHP so I have no idea how to do this. This is the code I have have now.
So how do I change the code to make it update data ?
<?php
include 'config.php';
$ID = $_GET['ID'] ;
$sql = "select * from table where ID = \"$ID\" and condition = false ";
// This is what I need the table to be updated "Update table where where ID = \"$ID\" set condition = true" ;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($data) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
one idea is to create a different database connection file consisting of a pdo connection and reuse it in your application. on how to do that.
in database.php you can do it like
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//catch the exception here and do whatever you like to.
}
and everywhere you want to use the connection you can do
require_once 'Database.php';
and some of the sample CRUD (Create, Read, Update, Delete) using PDO are.
//Create or Insert
$sth = $dbh->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$sth->execute();
//Read or Select
$sth = $dbh->query('SELECT name, addr, city from folks');
//Update
$sth = $dbh->prepare("UPDATE tablename SET col = val WHERE key = :value");
$sth->bindParam(':value', $value);
$sth->execute();
//Delete
$dbh->query('DELETE FROM folks WHERE id = 1');
you should also study about named and unnamed placeholders, to escape SQL injections etc. you can read more about PDO with a very easy to understand tutorial by nettuts here
hope this helps you.
Try this. I think it is along the lines of what you are looking for:
$query = "select * from table where ID = \"$ID\" and condition = false ";
$query_result = #mysql_query($query);
$query_row = mysql_fetch_assoc($query_result);
$update_query = "UPDATE table SET condition = true WHERE ID = {$row['ID']};";
if( #mysql_query($update_query) ) {
echo "Update succeeded!";
} else {
echo "Update failed!";
}
<?php
$ID = 1;
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$select_statement = $db->prepare('select * from table1 where id = :id and `condition` = false');
$update_statement = $db->prepare('update table1 set `condition` = true where id = :id');
$select_statement->execute(array(':id' => $ID));
$results = $select_statement->fetchAll();
$update_statement->execute(array(':id' => $ID));
echo '{"key":' . json_encode($results) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>

Categories