I'm facing a very strange problem. I have a SQL Server query which is very simple and working fine in any environment. I ran it and it was fine, but in my PHP, code doesn't work for some reason, and it returns empty array:
function conexion() {
$username = 'blahblah';
$password = 'blahblah';
try {
$pdo = new PDO ("odbc:SQL_FLOC", $username, $password);
$sql = $pdo->prepare(
"SELECT ent.id, pob.tmax from entradas AS ent INNER JOIN in_previsio_poblacio AS pob ON ent.id=pob.idpob");
$sql->execute();
$row = $sql->columnCount();
print_r($row);
}
catch (Exception $e) {
echo 'Conexión fallida', $e->getMessage();
exit;
}
}
i have changed INNER JOIN to LEFT RIGHT OUTTER and still get 0. Any idea?
UPDATE SAMPLE DATA:
this is the result i get by running the query in NAVICAT
Result of query:
Enteradas:
I cant share more than two picture, but I'm sure the table and query is just fine. The problem should be something about driver or something else.
In case who had the same problem here is the way i fixed it. I don´t know what was the problem but i changed the PDO driver and it works now. I was using the odbc driver and then i changed it to sqlsvr:
$pdo = new PDO ("sqlsrv:Server=FLOC\FLOC, 1473;Database=meteo", $username, $password);
Related
am using localhost and database from phpmyadmin
in php
<?php
$pdo = new PDO("mysql:host=localhost;port=3306;dbname=site_1", "root", "");
$query = "SELECT * FROM comment_v1";
$stmt = $pdo->prepare($query);
$avatars = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($avatars);
?>
in output
Array ( )
am working on games download site and i created 4 tables for now and all scripts working 100% without pb and the query the same but when i try to SELECT anything from table comment_v1 his apears nothing and idk the reason so i try to disable all the old query in scripts but the same result i got , but when i try code to SELECT the old query again his shows nothing with knowing that old query still working for now and idk why when i try to SELECT them again his show me nothing
Have you tried adding an execute() function before the fetchAll()?
something like:
<?php
$pdo = new PDO("mysql:host=localhost;port=3306;dbname=site_1", "root", "");
$query = "SELECT * FROM comment_v1";
$stmt = $pdo->prepare($query);
$stmt = $stmt->execute();
$avatars = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($avatars);
?>
I'm having the problem of mySQL not recognizing the session user when I select data from a table. Can someone please point me in the correct position on what I need to do to fix this?
$sql1="SELECT * FROM `Bookings` WHERE `username`={$_SESSION['user']}";
This is what my code looks like, but it never fetches the data and just remains blank.
First you should check if $_SESSION['user'] is initialized or has any value.
Second, it is better to assign the session user to a variable, so as to avoid some ugly issues related to escaping quotes, in the future. Don't just directly dump your session within your mysql statement.
$user_session = $_SESSION['user'];
$sql1="SELECT * FROM `Bookings` WHERE `username`= $user_session";
#Edit:
as #Dann pointed out, it's must better and safer to user prepared statement, with either the mysqli/pdo API. Here is a simple example in PDO.
First you have to connect to your database:
try {
$db = new \PDO("mysql:host=localhost;dbname=xx;charset=utf8", "xx", "xx", [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
} catch(\PDOException $e){
echo "Error connecting to mysql: ". $e->getMessage();
}
Then simply fetch the booking as seen below.
$user_session = $_SESSION['user'];
try{
$stmt = $db->prepare("SELECT * FROM Bookings WHERE username = ?");
$result = $stmt->execute([$user_session]);
if($result){
// show booking
}
} catch(\PDOException $e){
echo "Counld not get user bookings. error: " . $e->getMessage();
}
Now your query is safer from mysql injection attacks, and connection errors will only throw exceptions, instead of showing potentially harmful errors.
You can use
$user=$_SESSION['user'];
$sql1="SELECT * FROM Bookings WHERE username= '$user'";
Hopefully This will solve your problem
I am working on a project that is using a GoDaddy private server. Looks like the project is using mysql_connect to connect to the db.
I have worked with PDO before and figured I would just create a new file within the server so I can connect by using PDO. However I can't get it to work, and I can't get any errors to show up, nothing seems to happen when I run this code.
If I try to echo out a string after that block of code, the string wont show up, if I echo out a string before this block of code, the string will show up.
If I try to execute a prepared statement nothing happens. PW, UN, HOST, and db name are all correct. Am I doing something wrong?
<?php
error_reporting(E_ALL);
$dns = "mysql:host=localhost;dbname=mainsql;";
$username = "bowski";
$passwd = "kingsman1";
try {
$db = new PDO($dsn, $username, $passwd);
} catch (PDOException $ex) {
echo $ex->getMessage();
}
Here is a step-by-step procedure to enable PDO extension on Godaddy:
Login to your CPanel
Go to Web Hosting -> Manage for your domain
Click on Select PHP version menu
Now, you have the option to choose PHP version from the dropdown. Choose a different version than selected (e.g. 5.4 or 5.5) and then click Set as current.
After that, check the checkboxes of PHP extension you want on your site (e.g. PDO) and then click Save button present at the bottom.
Some host providers or even your own server might have PDO disabled or not installed per default. GoDaddy is one such provider.
I often see people struggling in similar situations thinking their PDO code is wrong, and asking the same question.
Therefore, it is always a good practice to check the availability of PDO driver before checking PDO code. One quick check is to perform the phpinfo(); call which dumps a (long) table of installed components.
Even if you have PDO installed, this is to ensure and guaranty that PDO driver is installed and running.
Add PDO driver checker code before your PDO code, saving you from some unnecessary debugging time:
if (!defined('PDO::ATTR_DRIVER_NAME'))
echo 'PDO driver unavailable';
I have exact same situation as what you described. After a big while of confusion and debugging, and I found out the reason / solution. But still not sure why Godaddy PDO has this issue.
PHP v5.4.45
<?php
$pdo = new PDO('mysql:localhost;dbname=mydb', $user, $pass);
$sth = $pdo->prepare('select * from tab limit 1');
$sth->execute();
$row = $sth->fetchAll();
echo '<pre>select * from test -- not working -- ';
print_r($row);
$sth = $pdo->prepare('select now()');
$sth->execute();
$row = $sth->fetchAll(PDO::FETCH_ASSOC);
echo "\nselect now -- working -- ";
print_r($row);
$sth = $pdo->prepare('show databases');
$sth->execute();
$row = $sth->fetchAll(PDO::FETCH_ASSOC);
echo "\nshow databases -- working -- ";
print_r($row);
$sth = $pdo->prepare('show tables');
$sth->execute();
$row = $sth->fetchAll(PDO::FETCH_ASSOC);
echo "\nshow tables -- not working -- ";
print_r($row);
$sth = $pdo->prepare('show privileges');
$sth->execute();
$row = $sth->fetchAll(PDO::FETCH_ASSOC);
echo "\nshow privileges -- working but not right -- ";
print_r($row);
$sth = $pdo->prepare('select * from information_schema.TABLES where TABLE_SCHEMA != \'information_schema\'');
$sth->execute();
$row = $sth->fetchAll(PDO::FETCH_ASSOC);
echo "\nselect * from information_schema.TABLES -- working -- ";
print_r($row);
No error -- how confusing. And I test this, works:
<?php
$pdo = new PDO('mysql:localhost;dbname=mydb', $user, $pass);
$sth = $pdo->prepare('select * from mydb.tab limit 1');
$sth->execute();
$row = $sth->fetchAll();
echo '<pre>select * from test -- working !!! -- ';
print_r($row);
And now I come up with this solution, but not sure if it is Godaddy PDO bug?
<?php
$pdo = new PDO('mysql:localhost', $user, $pass);
$sth = $pdo->prepare('use mydb');
$sth->execute();
$sth = $pdo->prepare('select * from tab limit 1');
$sth->execute();
$row = $sth->fetchAll();
echo '<pre>select * from test -- working !!! -- ';
print_r($row);
Conclusion:
It looks like Godaddy PDO does not use dbname, you need to manually run 'use dbname' after new PDO and before any other SQLs
I have a users table where I want to update the scores each time a user finishes the game. Unityscript part is working fine but after I post the score to the database it appears doubled or tripled. I post the score as int and also the table column is of int format. My PHP looks like this:
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = array(
':username' => $_POST['username'],
':score' => $_POST['score']);
$statement = $db -> prepare ("UPDATE users SET score = score + :score
WHERE username = :username");
$statement->execute($data);
}
catch(PDOException $e) {
echo $e->getMessage();
}
Any help or advice is appreciated.
You are using prepared statements, but you are still allowing injection by directly implementing the $score variable. Do the same thing with score that you did with username.
What do you mean by double or triple? Do you mean that the number is two or three times bigger? If so, try using a SELECT statement to fetch the score and do the math in PHP. Then, UPDATE the users table.
Doing this will allow you to better understand what you are doing wrong. Have you tried echoing the value of score within your try and catch to see if the value repeats? The code may be running more than once.
$statement = $db -> prepare ("UPDATE users SET score = :score
WHERE username = :username");
use this, i think it will work
i am new to PDO.
Here is what i have done so far,
Created file "pdotest.php"
Code Inside that file
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=houserentsystem;charset=utf8', 'root', 'admin');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$stmt = $conn->query("SELECT roomName FROM roomName.roomnames");
$results = $stmt->fetchAll();
$stmt->closeCursor();
print_r($results);
var_dump($results);
it should display some results from database but instead it says 500 internal server error in firebug, but no error on screen, its a white blank screen.
$stmt = $conn->query("SELECT roomName FROM roomName.roomnames");
try this instead:
$stmt = $conn->query("SELECT roomName FROM roomnames");
The select syntax is (basically):
SELECT column[, another_column, ...] FROM tablename[WHERE condition][ORDER BY some_column ASC/DESC];`
As you are setting the error mode to PDO::ERRMODE_EXCEPTION, you'll need to use try/catch to see any errors. This brings the burden of wrapping try/catch statements around your db queries.
Check your php log file for the exact php error - a white screen is shown as php is probably set up not to display errors on screen.
I'd check this part:
SELECT roomName FROM roomName.roomnames
Are you really trying to select roomName column from a table named roomName.roomnames? Should it not be the other way around like
SELECT roomnames FROM roomName
?