I am just using MS Access Database. I am trying to show the data of employee in the last of a year from MS Access Database using PDO prepare statement in PHP.
This is the code:
index.php
<?php
require_once "config.php";
date_default_timezone_set("Asia/Jakarta");
echo "<h3>Employee Data</h3><br><br>";
// START PDO SELECT
try {
$sql = "SELECT USERINFO.Name, USERINFO.Gender, CHECKINOUT.*, IIf(CHECKINOUT.Update = '', '[[ empty ]]', CHECKINOUT.Update) AS update_costum FROM CHECKINOUT
LEFT JOIN USERINFO ON CHECKINOUT.USERID = USERINFO.USERID
WHERE CHECKINOUT.CHECKTIME BETWEEN ? AND ?";
$dateFrom1 = "(Date()-360)";
$dateTo1 = "Date()";
//$dateFrom2 = date("d/m/Y H:i:s");
//$dateTo2 = date("d/m/Y H:i:s", strtotime("-1 years"));
$stmt = $link->prepare($sql);
$stmt->bindParam(1, $dateFrom1 );
$stmt->bindParam(2, $dateTo1 );
$stmt->execute(); // return -1 ?
echo $stmt->rowCount() . "<br><br>";
while ($ds_emp = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "User ID: " . $ds_emp["USERID"] . " || ";
echo "Nama : " . $ds_emp["Name"] . " " . $ds_emp["Gender"] . " || ";
echo "CHECKTIME : " . $ds_emp["CHECKTIME"] . " || ";
echo "Update : " . $ds_emp["update_costum"];
echo "<br>";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
After run the code, I get a couple of weird things.
The $stmt->rowCount(); return -1.
The $ds_emp only have a few data, not as expected. If I run the query directly in MS Access, the query return all of the data like what I expected.
The last line in the page show me this error.
SQLSTATE[22018]: Invalid character value for cast specification: -3030 [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression. (SQLFetchScroll[-3030] at ext\pdo_odbc\odbc_stmt.c:543)
Did I put wrong parameters or the query?
I think my query syntax is not wrong.
Why does $stmt->rowCount(); return -1?
Why are only few data stored in $ds_data variable?
How can I fix this?
The $link declaration variable is not shown here but to avoid this error it should be like this one
$dbName = "C:\\path\\to\\db.mdb";
$link = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)};charset=UTF-8; DBQ=$dbName; Uid=; Pwd=;");
Related
I got the following data in MySQL's JSON-type column:
{"2": [2, 3], "3": [29], "71": "test"}
I need to search array value inside of attribute "2", which works just fine when variables are placed inside the query, but not when using PHP's PDO arrays.
$field_id = 2;
$option_id = 2;
$query = "SELECT id FROM notes WHERE JSON_CONTAINS(data, '{\"$field_id\": $option_id }')";
try {
$stmt = $dbh->prepare($query);
$stmt->execute();
$used_qty = $stmt->rowCount();
} catch(PDOException $ex) {
echo 'Query failed: ' . $e->getMessage();
exit;
}
// $used_qty returns 1 which is correct;
Binding through array returns 0:
$query = "SELECT id FROM notes WHERE JSON_CONTAINS(data, '?')";
try {
$stmt = $dbh->prepare($query);
$stmt->execute(array('{"' . $field_id . '": ' . $option_id . '}"'));
$used_qty = $stmt->rowCount();
} catch(PDOException $ex) {
echo 'Query failed: ' . $e->getMessage();
exit;
}
Can't figure out what I missed here.
Please help. Thanks.
You quoted your placeholder:
$query = "SELECT id FROM notes WHERE JSON_CONTAINS(data, '?')";
^-^--
which means it's NOT a placeholder, it's a string containing a question mark.
Remove those quotes.
After enabling PDO exceptions:
$dbh = new PDO($dsn, $dsn_user, $dsn_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
I got clear error message saying that only value can be accepted as a second parameter:
Query failed: SQLSTATE[22032]: <>: 3141 Invalid JSON
text in argument 2 to function json_contains: "The document root must
not follow by other values." at position 8.
https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html#function_json-contains
But there is a third optional [path] parameter available: JSON_CONTAINS(json_doc, val[, path])
Which is exactly what I needed:
$query = "SELECT id FROM notes WHERE JSON_CONTAINS(data, ?, ?)";
try { $stmt = $dbh->prepare($query); $stmt->execute(array($option_id, '$."' . $field_id . '"')); $used_qty = $stmt->rowCount(); } catch(PDOException $ex) { echo 'Query failed: ' . $ex->getMessage(); exit; }
Thanks to Marc B.
I use PDO on my local computer to connect to MS SQL server to use prepare statements. The driver is installed properly and can connect to database. Here's the code:
try {
$con = new PDO("sqlsrv:Server={$host};Database={$db_name}", $username, $password);
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$query = "SELECT TOP 10 ClientID FROM CLIENT";
$stmt = $con->prepare($query);
$stmt->execute();
$num = $stmt->rowCount();
print $num;
From SSMS the query returns as it should, but nothing from the code as it prints -1 as the result of $num. If i change the query to SELECT ##VERSION it prints the version properly but not my query. My query is right from SSMS and PDO can connect to server but can't figure out where the problem is it's so frustrating please help.
can you try :
try {
$con = new PDO("sqlsrv:Server={$host};Database={$db_name}", $username, $password);
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$query = "SELECT TOP 10 ClientID FROM CLIENT";
$stmt = $con->prepare($query);
$stmt->execute();
$rows = $stmt->fetchAll();
$num = count($rows);
print $num;
// To print results :
foreach ($rows as $row) {
echo $row["ClientID"] . "<br/>";
}
New to mySQL PDO. I have read other answers here and read tutorials and am finally taking the plunge. Problem is I cannot seem to output data. Hence, can someone assess my code to ensure it is correct? Also, is the system I am using to query the db efficient and clean and secure? thanks
$pdo --- the correct connection information is in this line but has been removed ---
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// SELECT sql query
try {
$thedate='2013-06-03';
$rotation=1;
$stmt = $pdo->prepare("SELECT * FROM sched_main_2013 WHERE thedate=:thedate AND rotation=:rotation");
$stmt->bindValue(':thedate', $thedate, PDO::PARAM_STR);
$stmt->bindValue(':rotation', $rotation, PDO::PARAM_INT);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
}
catch(PDOException $ex) {
echo $ex->getMessage();
}
while($rows = $stmt->fetch()) {
echo $rows['thedate'] . "\n";
echo $rows[assignedRad] . "\n";
echo $rows[rotation] . "\n";
}
// close the connection
$pdo = null;
This code outputs nothing. No errors. Nothing at all.
By the way, the table exists and the SELECT * FROM works fine when I manually run the mySQL statement, so data does exist with this query.
Try
while($rows = $stmt->fetch()) {
echo $rows['thedate'] . "\n";
echo $rows[assignedRad] . "\n";
echo $rows[rotation] . "\n";
}
To
while($rows = $stmt->fetch()) {
echo $rows['thedate'] . "\n";
echo $rows['assignedRad'] . "\n";
echo $rows['rotation'] . "\n";
}
Debug 01
Maybe you can try this to test whether you truly receive any data from database
print_r($stmt->fetchAll());
Instead of your while-loop
Debug 02
Try the simple query that you strongly believe there will be no SQL error for example:
SELECT * FROM sched_main_2013
Without any value binding.
Debug 03
Try another query with WHERE condition, but no binding
SELECT * FROM sched_main_2013 WHERE thedate='2013-06-03' AND rotation=1
You told that var_dump($row) gives you FALSE. The documentation says:
The return value of this function on success depends on the fetch type. In all cases, >FALSE is returned on failure.
Add the following line:
while($row = $stmt->fetch()) {
echo $row['thedate'] . "\n";
echo $row['assignedRad'] . "\n";
echo $row['rotation'] . "\n";
}
if($row === FALSE) {
var_dump($stmt->errorInfo());
die();
}
Further note: You originally named the return value of $stmt->fetch() $rows (plural) instead of $row. I'm not sure whether you know that the method will return a single row each time it is called.
What it have to be
$sql = "SELECT * FROM sched_main_2013 WHERE thedate=? AND rotation=?";
$data = array('2013-06-03', 1);
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
$rows = $stmt->fetchAll();
var_dump($rows);
$sql = "SELECT * FROM sched_main_2013";
$data = array();
$stmt = $pdo->prepare($sql);
$stmt->execute(array());
$rows = $stmt->fetchAll();
var_dump($rows);
If second query returns the rows while first doesn't - there is no data found.
If both returns no rows - then it is caused by bad database design which is clearly seen from the table name, which should never have a postfix like this
I'm new to mysqli, I wrote a function as below.
1 - I couldn't find a way for SELECT * query and having bind_result to assign each column value to the same name variable. (e.g. name column value of #row stores to $name)
I think bind_result() has no function on a SELECT * query?
2 - So I tried another option, to fetch all rows and assign them to appropriate variable manually through a loop. I think I should use $query->fetch_all() or $query->fetch_assoc() for looping but I encounter with this:
Fatal error: Call to undefined method mysqli_result::fetch_all()
or
Fatal error: Call to undefined method mysqli_result::fetch_assoc()
However I did a phpinfo() and saw mysqlnd was enabled and php version is 5.4.7 (running XAMPP v1.8.1)
And 3- what finally I did is below idea that doesn't work either.
function the_names($name)
{
global $db;
if($query = $db->prepare("SELECT * FROM users where name=?"))
{
$query->bind_param('s', $name);
if($query->execute())
{
$query->store_result();
if($query->num_rows > 1)
{
while($row = $query->fetch())
{
echo $row['name']; // Here is the problem
}
}
else
echo "not valid";
$query->close();
}
}
}
I need a way to store all fetched data as what bind_result() does, or having them in an array for later use, and it's much better to know both. tnx
One word to answer all your questions at once - PDO
It has everything you are trying to get from mysqli (in vain):
function the_names($name)
{
global $db;
$query = $db->prepare("SELECT * FROM users where name=?");
$query->execute(array($name));
return $query->fetchAll();
}
$names = the_names('Joe');
foreach ($names as $row) {
echo $row['name'];
}
Note the proper way of using a function. it should never echo anything, but only return the data for the future use
If your mysqli code doesn't have binding_param() you can just write code like below :
$mysqli = new mysqli("localhost" , "root" , "" , "database_name");
$result = $mysqli->query( "SELECT * FROM users where name=" . $name) ;
while ( $row = $result->fetch_assoc() ) {
echo $row["name"];
}
If you use binding_param() code , you also need to set bind_result()
$db = new mysqli("localhost" , "root" , "" , "database_name");
function the_names($name){
global $db;
/* Prepared statement, stage 1: prepare */
if (!($query = $db->prepare("SELECT * FROM users where name=?"))) { # prepare sql
echo "Prepare failed: (" . $db->errno . ") " . $db->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$query->bind_param("s", $name)) { # giving param to "?" in prepare sql
echo "Binding parameters failed: (" . $query->errno . ") " . $query->error;
}
if (!$query->execute()) {
echo "Execute failed: (" . $query->errno . ") " . $query->error;
}
$query->store_result(); # store result so we can count it below...
if( $query->num_rows > 0){ # if data more than 0 [ that also mean "if not empty" ]
# Declare the output field of database
$out_id = NULL;
$out_name = NULL;
$out_age = NULL;
if (!$query->bind_result($out_id, $out_name , $out_age)) {
/*
* Blind result should same with your database table !
* Example : my database
* -users
* id ( 11 int )
* name ( 255 string )
* age ( 11 int )
* then the blind_result() code is : bind_result($out_id, $out_name , $out_age)
*/
echo "Binding output parameters failed: (" . $query->errno . ") " . $query->error;
}
while ($query->fetch()) {
# print the out field
printf("id = %s <br /> name = %s <br /> age = %s <br />", $out_id, $out_name , $out_age);
}
}else{
echo "not valid";
}
}
the_names("panji asmara");
Reference :
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
What is wrong with this code? I get an empty array. I am passing a PHP variable to the query, but it doesn’t work; when I give a hardcoded value the query returns a result.
echo $sub1 = $examSubject[$i];
$subType = $examType[$i];
$query = $this->db->query("select dSubject_id from tbl_subject_details where dSubjectCode='$sub1'");
print_r($query->result_array());
Look up “SQL injection”.
I’m not familiar with $this->db->query; what database driver are you using? The syntax for escaping variables varies from driver to driver.
Here is a PDO example:
$preqry = "INSERT INTO mytable (id,name) VALUES (23,?)";
$stmt = $pdo->prepare($preqry);
$stmt->bindparam(1,$name);
$stmt->execute();
failing to see what you database abstraction layer ($this->db) does, here's the adjusted code from example1 from the mysql_fetch_assoc documentation
<?php
// replace as you see fit
$sub1 = 'CS1';
// replace localhost, mysql_user & mysql_password with the proper details
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = 'SELECT `dSubject_id` ';
$sql .= 'FROM `tbl_subject_details` ';
$sql .= "WHERE `dSubjectCode` ='$sub1';";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['dSubject_id'];
}
mysql_free_result($result);
?>
Let me know what the output is, I'm guessing it will say: 6
Is it CodeIgniter framework you're using (from the $this->db->query statement). If so, why don't you try:
$this->db->where('dSubjectCode',$sub1);
$query = $this->db->get('tbl_subject_details');
If this doesn't work, you've got an error earlier in the code and $sub1 isn't what you expect it to be.