Using php/pdo to display sql data on website, no luck - php

I know this is probably something simple, but I have searched for hours the past few days and I'm ready to jump out of my one-story building.
Have a basic site for testing, literally nothing on it but opening/closing html tags.
A very basic table in a data base, using phpmyadmin to access it.
Trying to get table contents to display on the basic website.
Was using mysqli_ or mysql_ style in the php to access the data for a while with no luck.. Have since been reading about PDO and found numerous tutorials on how to use it. I feel like what I'm trying to do should be so simple but I've tried copying what I've found on this site and other tutorials to the T and the site still does not display the data.
try {
$conn = new PDO("mysql:host=$hostname; dbname=$userdb", $username, $password);
$conn->exec("SET CHARACTER SET utf8");
$sql = "SELECT * FROM Monday";
$result = $conn->query($sql);
while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {
echo $row['Name'] . '<br />';
}
$conn = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
Basically the website will display everything after the first -> in this case after the $conn-> but none of the actual table data.
I've tried about 50 different ways at least from numerous sites and I'm just lost now I guess..
Side note: I do have php forms on the same site that when submitted successfully insert data into the table, so I know I am able to connect to the db and table and INSERT, its just the issue of SELECT I can't get.
Thanks for any help
EDITED: to add fetchAll

You are using the method fetch() in your loop, which only fetches the next single row of your results. Replace it with fetchAll() and it should work.
More information about the fetchAll() method:
http://php.net/manual/en/pdostatement.fetchall.php
And for testing purposes you could set the PDO error mode to PDO::ERRMODE_EXCEPTION. See: http://php.net/manual/en/pdo.error-handling.php

while($row = $result->fetch(PDO::FETCH_ASSOC)) {
Should be;
while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {

Related

MySQL Returns different number of rows on localhost vs live server for the same code

I have a simple form that needs a list of stops in the textarea and returns an id for each on the right hand side. This is my screenshot on localhost...I have the same table names, column names, number of records on both localhost and live server.
Here's the screenshot of the same page with same query on live server...
Here's the code I am using on both pages
$conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
if(isset($_POST["busnumber"], $_POST["busroute"])){
$stops = explode(PHP_EOL, $_POST["busroute"]);
$sql = 'SELECT * FROM stops WHERE stop_name LIKE :stop';
$statement = $conn->prepare($sql);
$statement->setFetchMode(PDO::FETCH_ASSOC);
foreach($stops as $stop){
$statement->bindValue(':stop', $stop);
$statement->execute();
$results = $statement->fetchAll();
foreach($results as $result){
echo $result['stop_id'].' '.$result['stop_name']."</br>";
}
}
}
As you can see, it returns the ID of the last row only on the live server. Can someone please tell me how this is possible and what I am missing?
EDIT 1
Notice what happens when I reverse the data entered in the text area
The localhost shows both the ids now
Guess what the server shows after reversing? Only the LAST ROW!
You don't need setFetchMode(). In the time I've used PDO I always had the best results with just using bindParam() and fetch() with the most default setup of PDO, which means just setting the errormode to exception and charset to utf8 like this:
try
{
$con = new PDO("mysql:host=".$host.";dbname=".$db_name, $user, $password);
}
catch(PDOException $e){
die("ERROR ". $e->getMessage());
}
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->exec("SET NAMES utf8");
Fetching any results like this
while($r = $statement->fetch())
{
echo $r['id'];
}
Any time when someone has used a different set up, I've noticed they've faced problems.
Try this, perhaps.
This is very simple. Please check your live db via phpmyadmin if you have access and from phpmyadmin run your queries like you are running it from php code. May be you have some restrictions of mysql or php on live. And also check your db versions on localhost and live with php versions too. Let me know the results of phpmyadmin queries thanks!
Just guessing the problem. I don't really think if this answer is correct. So please pardon me in advance.
PDOStatement::fetchAll() returns an array that consists of all the rows returned by the query. From this fact we can make two conclusions:
This function should not be used, if many rows has been selected. In
such a case conventional while loop ave to be used, fetching rows
one by one instead of getting them all into array at once. "Many"
means more than it is suitable to be shown on the average web page.
This function is mostly useful in a modern web application that
never outputs data right away during fetching, but rather passes it
to template.
Source: PDO Tutorial
I FIXED the error. I have answered it in detail on a different post and I am linking to that post from HERE Thank you all for your time and answers

mysql dies everytime I try to create a new table

I am attempting to create new tables every time I post to this method, but for some reason I can not figure out why it dies.
<?php
$host = "127.0.0.1";
$username = 'cotten3128';
$pwd = 'pwd';
$database = "student_cotten3128";
$pin = $_REQUEST['pinSent'];
$words = $_REQUEST['resultSent'];
$tableName = $pin;
$db = new mysqli($host, $username, $pwd, $database);
if ($sql = $db->prepare("CREATE TABLE $pin (id INT(11) AUTO_INCREMENT);")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die('Could not create table');
}
for($i=0;$i<count($words);$i++){
if($sql = $db->prepare("INSERT INTO ".$pin.$words[$i].";")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die("Could not add data to table");
}
}
mysqli_close();
?>
Any help or insight would be greatly appreciated.
The intention of my post is to help you finding the issue by yourself. As you did not added much information I assume my post is helpful for you.
Based on the code you have shared I guess you mean one of your called die() functions is executed.
Wrong function call
As Jay Blancherd mentioned mysql_close is the wrong function. You rather have to use mysqli_close as you created a mysqli instance.
Beside of that mysql_* is deprecated and should not be used anymore.
Debugging Steps
Not only for this case but in general you should ask yourself:
Is there an error message available? (Frontend output, error log file, ...)
YES:
What's the message about?
Is it an error you can search for? E.g. via a search engine or the corresponding documentation?
Look up in the bug tracker (if available), by the software developer of the software you are using, and if it has not been reported yet report the issue.
NO: (if none error message available OR you cannot search for it as it is a custom error message)
Search in the files of the software you are using for the error message and start a core-debugging.
STILL NO SOLUTION?:
Ask on stackoverflow.com e.g. and tell your issue and the steps you have performed to find and fix the bug. Post only as much code as necessary plus use a proper format.
Debugging in your case:
In order to narrow down the scope. Which of the die() is executed? Depending on that echo the query to execute just before it actually is executed. Then copy the SQL query to an SQL editor and look at it syntax. After that you probably know the problem already.

How to fetch value with Cassandra PDO?

I am using a PHP PDO driver for an application that uses Apache Cassandra and I cannot fetch the information I need. Is anything obviously wrong?
$db = new PDO('cassandra:host=localhost;port=9160');
$db->exec("USE project");
$st = $db->prepare("SELECT fname FROM users WHERE email=:em;");
$st->bindValue(':em', 'email1#gmail.com', PDO::PARAM_STR);
$st->execute();
print_r($st->fetch(PDO::FETCH_ASSOC));
Nothing is printed to the window. The table users was created with the email column as the primary key. I had no trouble inserting and updating information to the users table in my app, but still cannot figure out how to fetch single values successfully. Similarly, when I fetchAll() with some query I can print the arrays (rows) to the screen but cannot index them to grab specific values. Maybe there is some detail about cassandra that I am missing?
Do the following:
Check the return values of each method.
Check if there is an error after executing the statement.
Check the error log of your php interpreter.
$db = new PDO('cassandra:host=localhost;port=9160');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$db->exec("USE project");
$st = $db->prepare("SELECT fname FROM users WHERE email=:em;");
if ($st == false) {
print_r($db->errorInfo())
exit;
}
if ($st->bindValue(':em', 'email1#gmail.com', PDO::PARAM_STR) == false) {
print_r($db->errorInfo())
exit;
}
if ($st->execute() == false) {
print_r($db->errorInfo())
exit;
}
print_r($st->fetch(PDO::FETCH_ASSOC));
I had a similar problem. I used YACassandraPDO. Unfortunately when use it with php 5.4 I get error 502. Decided to write his or her library that allowed to work with Cassandra binary protocol without experiencing similar problems.
In the future, I plan to speed it up.
Maybe it will help you. Syntax like PDO.

MySQL Tables Not Updating (PDO)

I am trying to have the PHP code update an address in user table.
For starters, using mysqli, and tried both prepared statements as well as simpler queries. Never had much luck with prepared statements ever because I find them confusing, particularly bind_result().
I do use mysql testing at the command itself to make sure it works as it should. Updates as it should so it's not the mysql command itself. I even gave it a shot in phpMyAdmin locally on the server. However, once in PHP, it doesn't update data in the table.
Immediate thought that came to mind was to make sure the 'user' accessing the mysql tables had UPDATE rights, and it does. So it doesn't look like a permission issue. Even when I use the mysql root with all rights and privileges, the table will NOT update.
My original attempt was some thing quite simple:
$query = "UPDATE `UserTable` SET `Address`=\"". $address . "\" WHERE `id`=".$id;
$conn->query($query);
So, I tried prepared statement version of this and had the same effect. No error, but nothing changed in my table.
Today, I decided to go the PDO route.
try {
$dbh = new PDO("mysql:host=$hostname; dbname=DBDatabase", $db_user, $db_pass);
$query = "UPDATE UserTable SET 'Address'='".$address."' WHERE 'id'=".$id;
echo "Query: ". $query;
$count = $dbh->exec($query);
echo $count . " record changed.";
$dbh = null;
}
catch (PDOException $e) {
echo $e->getMessage();
}
I also tried changing other fields (maybe it was just happening to VARCHAR fields like address). So, I tried flipping the Registered flag and no changes register for that either.
You're not using PDO properly. This is how you will want to form your query.
try {
$dbh = new PDO('mysql:host=$hostname; dbname=DBDatabase', $db_user, $db_pass);
$stmt = $dbh->prepare('UPDATE UserTable SET `Address`=:address WHERE `id`=:id');
$stmt->bindParam(':address', $address, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
}
catch (PDOException $e) {
echo $e->getMessage();
}
This is not your direct question, but prepared statements are super easy, they just require a learning curve - which, honestly, from personal experience is no steeper than learning PDO.
Traditional Query Steps:
DB query.
DB result.
Prepared Query:
Send DB query without parameters, to prepare.
Insert parameters.
Connect to results (bind a variable for each return column, in order).
Cycle through results, using variables rather than a $result array.
It is a few extra steps, but take the twenty minutes you need to to conceptualize it and it will all snap together. The advantage to PDO is that it works across different databases and it is great at prepared statements.

PHP General SQL Query and Results similar to PhpMyAdmin

I am having trouble creating a general MySQLi query box, where the results, regardless of the type of query, are output in another textarea - similar to the textarea from the SQL tab in PHPMyAdmin.
For example:
I would like to display a textarea on my page.
User enters ANY MySQL code, whether it be SELECT, UPDATE, DELETE, etc.
Results are displayed in a results textarea, for example, if they enter a SELECT query, they get the results, if they enter a DELETE, they will get a # of deletions.
Functions just like the SQL tab of PHPMyAdmin.
Is there a simplified way to do this? Or do I need to detect their query, and return results depending on an algorithm that I have to write (which I can do, I'm just trying to avoid all that coding).
This is what I've tried last:
$mysqli = new mysqli($host, $username, $pw, $dbname);
if ($mysqli->connect_errno) {
echo "BAD CONNECTION!";
} else {
$result = $mysqli->query($query);
print_r($result);
mysqli_free_result($result);
}
$mysqli->close();
I also tried:
echo $result
Thanks!
There is no simple way to do what you need. Try to use some PHP open source DB libraries like DiBi (http://dibiphp.com/cs/). But you will still need to write some code. This just makes it easier.

Categories