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);
Related
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.
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);
I have made a code using PDO to read a table from a database.
I try to echo my result but I get a blank page without error.
My Code Is:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
But the echo is empty without any error.
What I am doing wrong?
Thank you All!
Few things to change:
dont forget $
if your going to catch the error, catch the whole pdo code
You can use rowCount() to count the rows
echo something if the record count is 0
include 'config.php';
$id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->rowCount() != 0)
{
$row = $result->fetch(PDO::FETCH_BOTH);
echo $row['Data1'];
echo $row['Data2'];
}else{
echo 'no row found';
}
}catch(PDOException $e){
echo "error " . $e->getMessage();
}
Also use prepared statements for example:
$result = $conn->prepare("SELECT * FROM mytable WHERE id=:id");
$result->execute(array(':id'=>$id));
I'm assuming there's only one record with the id "264540733647332".
The issue is that $result->fetchColumn() call reads first row in the result set and then advances to the next result. Since there's only one of the results, the subsequent call to $result->fetchAll() returns nothing, hence no data displayed.
To fix this replace fetchColumn with rowCount:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
is anyone able to find out what went wrong in this code below? It just shows a blank page. I'm new to PDO, always used mysqli but someone told me to try PDO since my page had problems showing arabic characters.
<html>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1;charset=UTF8;'
$user = 'dbuser'; // don't hardcode this...store it elsewhere
$password = 'dbpass'; // this too...
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT :column FROM :table";
$opts = array(
':column' => 'Name',
':table' => 'Mothakirat'
);
$dbh->beginTransaction();
$statement = $dbh->prepare($sql);
if ($statement->execute($opts)) {
$resultArray = array(); // If so, then create a results array and a temporary one
$tempArray = array(); // to hold the data
while ($row = $result->fetch_assoc()) // Loop through each row in the result set
{
$tempArray = $row; // Add each row into our results array
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray); // Finally, encode the array to JSON and output the results
}
$dbh->commit();
</html>
This has no parse errors checked in my IDE. I use netbeans, its very good and available on several platforms.
<html>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1;charset=UTF8;';
$user = 'dbuser'; // don't hardcode this...store it elsewhere
$password = 'dbpass'; // this too...
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT :column FROM :table";
$opts = array(
':column' => 'Name',
':table' => 'Mothakirat'
);
$dbh->beginTransaction();
$statement = $dbh->prepare($sql);
if ($statement->execute($opts)) {
$resultArray = array(); // If so, then create a results array and a temporary one
$tempArray = array(); // to hold the data
while ($row = $result->fetch_assoc()) // Loop through each row in the result set
{
$tempArray = $row; // Add each row into our results array
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray); // Finally, encode the array to JSON and output the results
}
$dbh->commit();
?>
</html>
I am using the following code for reading a String from a mysql function:
<?php
print_r($_POST);
try {
$dbh = new PDO("mysql:dbname=mydb;host=myhost", "myuser", "mypass" );
$value = $_POST['myLname'];
print $value ;
//print $dbh ;
$stmt = $dbh->prepare("CALL check_user_exists(?)");
$stmt->bindParam(1, $value, PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 50);
// call the stored procedure
$stmt->execute();
print "procedure returned $value\n";
echo "PDO connection object created";
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
This is not reading the returned value , however if I read the value usimg mysql* like :
<?php
$dbhost='myhost';
$dbuser='mydb';
$dbpassword='mypass';
$db='mydb';
$con=mysql_connect($dbhost, $dbuser, $dbpassword) or die("Could not connect: " . mysql_error()); ;
mysql_select_db($db,$con);
$qry_str = "select check_user_exists('chadhass#hotmail.com')";
$rset = mysql_query($qry_str) or exit(mysql_error());
$row = mysql_fetch_assoc($rset);
mysql_close($con);
foreach($row as $k=>$v)
{
print $k.'=>'.$v;
}
?>
This returns correctly . ANy idea wha am I missing ?
function :
CREATE
FUNCTION `check_user_exists`(in_email
VARCHAR(100)) RETURNS varchar(1) CHARSET utf8
READS SQL DATA
BEGIN
DECLARE vcount INT;
DECLARE vcount1 INT;
SELECT COUNT(*) INTO vcount FROM USERS
WHERE USEREMAIL=in_email;
IF vcount=1 then
SELECT COUNT(*) INTO vcount1 FROM USERS
WHERE USEREMAIL=in_email and isactive=1;
if vcount1=1 then
return('1');
else
return('0');
end if;
ELSE
RETURN('2');
END IF;
END
code that worked for PDO ::
<?php
//print_r($_POST);
try {
$dbh = new PDO(PDO("mysql:dbname=mydb;host=myhost", "myuser", "mypass" );
$value = $_POST['myLname'];
$result = $dbh->prepare("select check_user_exists(?) as retval");
$result->bindParam(1, $value, PDO::PARAM_STR, 2);
$result->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
$result->execute();
$obj = $result->fetch();
print($obj->retval);
echo "PDO connection object created";
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
The reason is, you aren't fetching the results from the query.
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);