PHP PDO, connection works buy query not executing - php

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
?

Related

How to handle PDO Fatal error when table is not exist?

I want to print the convenient error message(user understandable message ) instead of PDO system fatel error.
I have the following PDO statement, if that table not exist I want to print error message table is not exist.
$db = new PDO('mysql:host=localhost;dbname=cnf20;charset=utf8mb4', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
function getData($db) {
$stmt = $db->query("SELECT * FROM tb_accessory_info1");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
try {
foreach(getData($db) as $row) {
echo $row['part_no'];
}
} catch(PDOException $ex) {
$db->rollBack();
echo $ex->getMessage();
}
Currently I'm getting this error message
Fatal error: Uncaught PDOException: There is no active transaction
in......on line 15
Instead of this I wanted to print user understandable error message like 'Please try again!'
Please support me! Thanks
As Paul said, it's not clear why you would want to query a table that doesn't exist, but one way is to check for the existence of the table in MySQL before running your other statements:
SELECT *
FROM `information_schema`.`tables`
WHERE `table_schema` = 'database_name' AND `table_name` = 'table_name'
LIMIT 1;
This assumes the user connecting to the database has read access on information_schema.tables. Replace 'database_name' and 'table_name' with your values.

need to SELECT and show all entries written by specific user and count it

I need to SELECT and show all entries written by specific user and number of his/her total entries
<?php include 'helperl.php'; include 'dbconn.php';
$name=$_GET['id'];
$sql="SELECT * FROM entries WHERE writer_user LIKE '%$name%'";
$result=$conn->query($sql);
$num_entry= count($result);
echo "$num_entry";
?>
First the LIKE option that you did will get you all the name that contain $user
Your query should be like
SELECT nb
FROM (SELECT writer_user,count(*) as nb
FROM entries
WHERE writer_user=you_var
Group BY writer_user)
For getting all the entries of specific user
SELECT *
FROM entries
WHERE writer_user=you_var
u can do a join in one query to get the information you wanted but there will be a duplication in the count attribut.
exemple :
entrie count
entrie1 4
entrie2 4
entrie3 4
entrie4 4
hope i helped you.
you should use SQL COUNT function to do this (SQL COUNT function
)
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Your code can look like this
<?php
try {
$name = htmlentities(strip_tags($_GET['id']));
$sql = "SELECT COUNT(writer_user) as counter FROM entries WHERE writer_user LIKE '%$name%'";
// create pdf instance
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("SELECT COUNT(writer_user) as counter FROM entries WHERE writer_user LIKE '%name%'");
$stmt->bindParam('name', $name);
$stmt->execute();
$result = $conn->query($stmt)->fetchAll();
var_dump($result);
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
$conn = null;
?>

INNER join doesn't work with PDO in PHP

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

LIKE query in PDO not working

PDO queries run fine, but when i try to use LIKE query it don't work and give error. i know i am doing something wrong, please if anyone can point out where i have gone wrong and how to run the the LIKE query properly.
<?php
/**
* Created by PhpStorm.
* User: HaiderHassan
* Date: 9/3/14
* Time: 9:52 PM
*/
header('Access-Control-Allow-Origin: *');
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();
}
if($_POST['searchFilter']){
$searchFilter = "%".$_POST['searchFilter']."%";
echo $searchFilter;
$stmt = $conn->query("SELECT roomName FROM roomnames WHERE roomName LIKE".$searchFilter);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
print_r(json_encode($results));
}
i have two columns in table(roomnames) roomID and roomName
i want to get the result of data which matches with the posted value.
You have multiple problems:
a) Vulnerable to SQL injection attacks
b) Lacking a space after LIKE, which means you're producing
... LIKE%foo%
c) Lack of quotes around your search parameter, so even if you did fix b), you'd still have a problem. it should be
... LIKE '$searchParameter'
^----------------^--- note the quotes
The statement should be prepared
if($_POST['searchFilter']){
$searchFilter = $_POST['searchFilter'];
echo $searchFilter;
try {
$conn = new PDO('mysql:host=localhost;dbname=houserentsystem;charset=utf8', 'root', 'admin');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT roomName FROM roomnames WHERE roomName LIKE ?");
$stmt->execute(array('%'.$searchFilter.'%'));
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//print_r($results);
echo json_encode($result);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
In this line:
$stmt = $conn->query("SELECT roomName FROM roomnames WHERE roomName LIKE".$searchFilter);
There has to be a space behind the LIKE
You need to enclose the string between apostrophs to make it an actual SQL string
You should definitely use parametrized queries, because right now this is a gaping SQL injection hole (what if someone searches for ';delete from roomnames; select '?)

Is it possible to run a mysqli query directly via the link while a statement is opened?

I'm trying to do a simple operation on a MySQL database: my contacts have their complete names on a column called first_name while the column last_name is empty.
So I want to take what's on the first_name column and split it on the first occurrence of a white space and put the first part on the first_name column and the second part on the last_name column.
I use the following code but it's not working:
$connection = new mysqli(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME, DATABASE_PORT);
$statement = $connection->prepare("SELECT id, first_name FROM contacts");
$statement->execute();
$statement->bind_result($row->id, $row->firstName);
while ($statement->fetch()) {
$names = separateNames($row->firstName);
$connection->query('UPDATE contacts SET first_name="'.$names[0].'", last_name="'.$names[1].'" WHERE id='.$row->id);
}
$statement->free_result();
$statement->close();
$connection->close();
Can I use the $connection->query while having the statement open?
Best regards.
UPDATE
The $connection->query(...) returns FALSE and I get the following error:
PHP Fatal error: Uncaught exception 'Exception' with message 'MySQL Error - 2014 : Commands out of sync; you can't run this command now'
I changed the code to the following and worked:
$connection = new mysqli(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME, DATABASE_PORT);
$result = $connection->query("SELECT id, first_name FROM contacts");
while ($row = $result->fetch_row()) {
$names = separateNames($row[1]);
$connection->query('UPDATE contacts SET first_name="'.$names[0].'", last_name="'.$names[1].'" WHERE id='.$row[0]);
}
$connection->close();
Can I use the $connection->query while having the statement open?
Yes. It will return a new result object or just a boolean depending on the SQL query, see http://php.net/mysqli_query - In your case of running an UPDATE query it will always return a boolean, FALSE if it failed, TRUE if it worked.
BTW, the Mysqli connection object is not the Mysqli statement object, so they normally do not interfere with each other (disconnecting might destroy/break some statements under circumstances, but I would consider this an edge-case for your question you can ignore for the moment).
I wonder why you ask actually. Maybe you should improve the way you do trouble-shooting?
I can only have one active statement at a given time, so I had to make one of the queries via the $connection->query() method.
As #hakre mentioned:
I still keep my suggestion that you should (must!) do prepared statements instead of query() to properly encode the update values
I opted to use the statement method for the update query, so the final working code is the following:
$connection = new mysqli(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME, DATABASE_PORT);
$result = $connection->query("SELECT id, first_name FROM contacts");
$statement = $connection->prepare("UPDATE contacts SET first_name=?, last_name=? WHERE id=?");
while ($row = $result->fetch_row()) {
$names = separateNames($row[1]);
$statement->bind_param('ssi', $names[0], $names[1], $row[0]);
throwExceptionOnMySQLStatementError($statement, "Could not bind parameters", $logger);
$statement->execute();
throwExceptionOnMySQLStatementError($statement, "Could not execute", $logger);
}
$statement->free_result();
$statement->close();
$connection->close();
Thanks to all that gave their inputs, specially to #hakre that helped me to reach this final solution.

Categories