PHP PDO Data_length always returns "0" - php

Well, I'm just trying the following for around two hours now and I can't get it to work. The following code will always return "0". Please, can anyone see where is the problem. This should work as a charm. And in PhpMyAdmin, when I run the statement it works correctly.
Actually, this is a copy/pasted code from another question here on SO which was accepted as a working answer. Check it out here.
EDIT:
No errors are thrown using:
error_reporting(-1); and
PDO::ERRMODE_EXCEPTION.
UPDATE:
Definitely, I'm getting only the first row from the query where the Data_lenght is "0". I've tested also fetchAll, and also trying to access the Data_length index while fetching. No luck.
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<?php
try {
error_reporting(-1);
$host_name = "my_hsot";
$database = "my_db";
$user_name = "my_user";
$password = "my_pwd";
$conn = new PDO("mysql:host=$host_name;dbname=$database", $user_name, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->query('SHOW TABLE STATUS');
$dbSize = 0;
$row = $sth->fetch(PDO::FETCH_ASSOC);
$dbSize = $row["Data_length"];
$decimals = 2;
$mbytes = round($dbSize/(1024*1024),$decimals);
echo $dbSize . "\n" . $row["Data_length"];
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
</body>
</html>
Any help is appreciated.

PDO always returns "0" because $row = $sth->fetch(PDO::FETCH_ASSOC); returns only the first row from the query, and the index of Data_length there is "0", as it could be any other value.

Related

Warning: Illegal string offset - Syntax [duplicate]

I'm using the following code to make a connection to the database, fetch the Data_length index column, and calculate the database size based on the data.
For some reason PDO will always return "0", which is the value for the Data_length index in the first row. Whatever I do, I only get the first rows index.
The database is MySQL, the engine MyISAM.
PHP Version: 5.5.38
MySQL Version: 5.5.50
Here is the source code.
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<?php
try {
error_reporting(-1);
$host_name = "my_host";
$database = "my_db";
$user_name = "my_user";
$password = "my_pwd";
$conn = new PDO("mysql:host=$host_name;dbname=$database", $user_name, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->query('SHOW TABLE STATUS');
$dbSize = 0;
$row = $sth->fetch(PDO::FETCH_ASSOC);
$dbSize = $row["Data_length"];
$decimals = 2;
$mbytes = round($dbSize/(1024*1024),$decimals);
echo $dbSize . "\n" . $row["Data_length"];
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
</body>
</html>
Add a while loop,
while($row= $sth->fetch( PDO::FETCH_ASSOC )){
echo $row['your_field_name'];
}
Or you can use fetchAll
$rows = $sth->fetchAll();
print_r($rows);

PDO fetch returns only first row

I'm using the following code to make a connection to the database, fetch the Data_length index column, and calculate the database size based on the data.
For some reason PDO will always return "0", which is the value for the Data_length index in the first row. Whatever I do, I only get the first rows index.
The database is MySQL, the engine MyISAM.
PHP Version: 5.5.38
MySQL Version: 5.5.50
Here is the source code.
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<?php
try {
error_reporting(-1);
$host_name = "my_host";
$database = "my_db";
$user_name = "my_user";
$password = "my_pwd";
$conn = new PDO("mysql:host=$host_name;dbname=$database", $user_name, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->query('SHOW TABLE STATUS');
$dbSize = 0;
$row = $sth->fetch(PDO::FETCH_ASSOC);
$dbSize = $row["Data_length"];
$decimals = 2;
$mbytes = round($dbSize/(1024*1024),$decimals);
echo $dbSize . "\n" . $row["Data_length"];
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
</body>
</html>
Add a while loop,
while($row= $sth->fetch( PDO::FETCH_ASSOC )){
echo $row['your_field_name'];
}
Or you can use fetchAll
$rows = $sth->fetchAll();
print_r($rows);

My openshift application PDO query didn't work

I am try to connect phpmyadmin database using my php script in openshift
but the result is a empty page.
then, I find the question is the query didn't work
but I don't know why
There is my original code
try{
$dsn = 'mysql:dbname=exampleDataBase;host=127.**.***.***;port=*****';
$dbh = new PDO($dsn, "account", "password");
$sth = $dbh->prepare('SELECT * FROM test1');
$fin = $sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)){
print_r($row);
}
} catch (PDOException $e){
echo "Sytan error" . $e -> getMessage();
}
$dbh = null;
and the result is a empty page, so I modify my code
There is my modify code
try{
$dsn = 'mysql:dbname=exampleDataBase;host=127.**.***.***;port=*****';
$dbh = new PDO($dsn, "account", "password");
$sth = $dbh->prepare('jngfcjfgcnmgcm,,hmnxf');
$fin = $sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)){
print_r($row);
}
} catch (PDOException $e){
echo "Sytan error" . $e -> getMessage();
}
$dbh = null;
I input the wrong query sytanx(jngfcjfgcnmgcm,,hmnxf), but it didn't return error.
Add this to your script see your errors
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',1);
ini_set('html_errors', 1);
and change your query code to this, see notes
try{
//port=***** is only need where its different from the default
$dsn = 'mysql:host=localhost;dbname=exampleDataBase';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dbh = new PDO($dsn, "account", "password", $options);
$sth = $dbh->prepare('SELECT * FROM test1');
// execute $sth
$sth->execute();
//Change fetch to fetchAll
while($row = $sth->fetchAll(PDO::FETCH_ASSOC)){
print_r($row);
}
} catch (PDOException $e){
echo "Sytan error" . $e->getMessage();
}
You modified your code to a wrong statement to see the error message?
You have your PHP errors turned off, when doing a statement like:
$sth = $dbh->prepare('jngfcjfgcnmgcm,,hmnxf');
You would receive an error like:
Sytan errorSQLSTATE[42000]: Syntax error or access violation: 1064 You
have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near
'jngfcjfgcnmgcm,,hmnxf' at line 1
What do you exactly want? The exception is not showing?

PDO/SQL insert not working

got the following code. All values are gotten through javascript and then sent through ajax. The var_dump($array) at the end works and display all the correct values. So they are all passed through correctly. The catch error for the try method also never pops up. The values are not being inserted into the sql table. Whats wrong?
Thanks in advance.
$name = $_GET['name'];
$category = $_GET['category'];
$subCategory = $_GET['subCategory'];
$date = $_GET['date'];
$address = $_GET['address'];
$city = $_GET['city'];
$state = $_GET['state'];
$host = $_GET['host'];
$imagePath = $_GET['imagePath'];
$info = $_GET['info'];
//turn into array
$array = array();
$array[0]=$name;
$array[1]=$category;
$array[2]=$subCategory;
$array[3]=$date;
$array[4]=$address;
$array[5]=$city;
$array[6]=$state;
$array[7]=$host;
$array[8]='j';//$imagePath;
$array[9]=$info;
try {
$con = new PDO('mysql:host=localhost;dbname=test');
$insert = $con->prepare(" INSERT INTO create
(name,category,subCategory,date,address,city,state,host,imagePath,info)
VALUES (?,?,?,?,?,?,?,?,?,?) ");
$insert->execute($array);
}
catch(PDOException $e) { //try
echo 'error';
//echo 'ERROR: ' . $e->getMessage();
}
var_dump($array);
create is a reserved word in mysql so you need to quote it in backticks:
INSERT INTO `create` ...
To have PDO throw exceptions, you need to add that after you open your connection:
$con = new PDO('mysql:host=localhost;dbname=test');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
By the way, I assume that you are logging into your database with a username and a password as well (the second and third parameter of the PDO constructor)...

MySQL MATCH, AGAINST not works with PDO

I have this simple code to make search results depending on relevance:
$stmt = $db->query('SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")');
$appCount = $stmt->rowCount();
echo $appCount;
And it's not showing any results!
Thanks in advance for your help,
Marcell
Stackoverflow's usability is below zero.
Because there is no way to make a half-screen banner shown to everyone posting a question under PDO tag:
Enable ERRMODE_EXCEPTION when connecting to PDO before asking a question.
Because it is pointless to ask without an error message, yet error message most likely will render a question unnecessary.
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
$pdo = new PDO($dsn,'root','', $opt);
Try
'SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")'
in phpmyadmin and see if it really returns anything.
try this
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';
try {
// Connect and create the PDO object
$db = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$db->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")";
$stmt = $db->query($sql);
// If the SQL query is succesfully performed ($stmt not false)
if($stmt !== false) {
$cols = $stmt->columnCount(); // Number of returned columns
echo 'Number of returned columns: '. $cols. '<br />';
// Parse the result set
foreach($stmt as $row) {
echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
}
}
$db = null; // Disconnect
}
print_r($sth->errorInfo());
}
?>
enclose your code in try and catch blocks, then you should get a clue to where your going wrong in your SQL syntax:
try {
// your code
} catch ( PDOException £e ) {
echo $e->getMessage();
exit();
}

Categories