I am trying to build a customer e-commerce backend. I've done stuff like this many times before and don't consider myself "new" to php & mysql, but I am stuck and can't figure out what is wrong.
I just want to display the content of a mysql row at a specific location (using the "WHERE" command).
But when I load the page, the content part (in the tables) comes up empty. There is definitely content within the table at that location and everything else on the page displays EXCEPT for the actual customerResults.
Here is my code:
<head>
<title>Customer Summary</title>
<?php
session_start();
require 'database_connect.php';
$customerTable = "customer";
if(isset($_GET['customer_click'])){
$customerId = $_GET['customer_click'];
}
?>
</head>
<h3>Customer <?php echo"$customerId"?></h3>
<table align="center" width="600px">
<tr>
<td>Summary</td>
<td>Personal</td>
<td>Billing</td>
<td>Order History</td>
</tr>
</table>
<table align="center" width="400px">
<tr>
<?php
$customerSelect = "SELECT * FROM $customerTable WHERE id = '$customerId' ";
$customerResult = mysql_query($customerSelect);
if (!$customerResult){
echo "No results, but why?!?!? </br/>";
}
if (mysql_num_rows($customerResult)==0){
echo "Results are empty...but why!?!?!";
}
while ($customerData = mysql_fetch_assoc($customerResult)){
echo $customerData['id'];
echo $customerData['email'];
}
?>
</tr>
</table>
I could be over-looking something simple, but I really can't figure this out
Let's see:
Line 27: Undefined variable 'customerSelct'.
Line 41: Undefined variable 'customerDdata'.
Line 43: Undefined variable 'result'.
Plus Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Example code using PDO:
<?php
try {
session_start();
if (!isset($_GET['customer_click'])) {
throw new Exception('Customer ID not provided.');
}
//Assuming the ID must be a number.
if (!is_numeric($_GET['customer_click'])) {
throw new Exception('Customer ID must be numeric.');
}
$customerID = $_GET['customer_click'];
$db = new PDO("mysql:host=localhost;dbname=database_name_here", "user", "pass");
//Have PDO to not emulate prepared statements by default.
//Instead use MySQL's native prepare engine.
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//PDO will throw PDOExceptions on every error.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM `customer` WHERE `id` = :id";
$stmt = $db->prepare($query);
//Bind ID as a number and not as string.
$stmt->bindValue(":id", $customerID, PDO::PARAM_INT);
$stmt->execute();
//Fetch all results into $result.
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $e) {
//A database error has occurred!
die("Database Error occurred! " . $e->getMessage());
}
catch (Exception $e) {
//General error occurred!
die("Error! " . $e->getMessage());
}
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<pre>
<?php print_r($result); ?>
</pre>
</body>
</html>
Related
I am converting an old php 5.6 code to 7.2 and learning how to use PDO.
I have reached a point where I got stuck and would like to learn from the community.
I created a test file structure:
db.php:
<?php
try {
$conn = new PDO($initlocation, $username, $pwdata);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "worked"; // THIS WORKS ON THE SCREEN
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
?>
test.php:
<?php
include("db.php");
$user_query='SELECT * FROM `users` WHERE `email`="user1.a#gmail.com"';
echo $user_query; // I GET THE QUERY PRINTED ON THE SCREEN
echo is_object($conn); // THIS IS 1 WHICH IS GOD
echo "<br>";
echo is_object($res); // THIS IS 1 WHICH IS ODD
try{
$res = $conn->query($user_query);
}
catch (Exception $e){
echo "Query failed: " . $e->getMessage(); // NOTHING
}
echo "<br>";
echo is_object($res); // NOTHING
$data_exists = $res->fetch();
if ($data_exists==1) echo "yes"; // NOTHING
?>
I have left the testing method in the code as well and I am keen to find a better solution to find out why the query does not show anything.
The aim would be to find the email address in the DB and give me some feedback about it. Thank you in advance all the comments I will only learn form them.
Additional info:
When I run the SQL query in the DB directly it does give me the record that has the same email.
Try the following and use prepared statements like protection from SQL injections.
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();
So I'm working on a PHP Pastebin-esque project on my freetime to learn PHP and server management, and I've run into a LOT of issues, and I haven't been able to solve them. I decided to restart from sratch on my own with the information I've gathered so far, and threw this code together.
<?php
require 'connection.php';
$getid = $_GET["id"];
$sql = 'SELECT paste FROM pasteinfo WHERE id=:id';
$stmt = $con->prepare($sql);
$stmt->bind_param(':id', trim($_GET["id"], PDO::PARAM_INT));
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['paste'];
}
?>
What I'm trying to achieve with this code is a system where a user can type the id of whatever paste they're interested in viewing in the url and have it display the pasteinfo row, which is the row that holds the paste itself. The format they should have is viewpaste.php?id=(user input).
How can I fix this code? I would also greatly appreciate if you explain whatever code you might end up putting in the comments so I can learn from it. Thanks!
Try this;
connection.php
try{
$db = new PDO('mysql:host=localhost;dbname=database_name;charset=utf8mb4', 'database_username', 'database_password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $ex){
echo $ex->getMessage();return false;
}
function retrieve($query,$input) {
global $db;
$stmt = $db->prepare($query);
$stmt->execute($input);
$stmt->setFetchMode(PDO::FETCH_OBJ);
return $stmt;
}
To retrieve data, call the retrieve() function
Retrieval page, say display.php
require 'connection.php';
$getid = $_GET["id"];
$result=retrieve("SELECT paste FROM pasteinfo WHERE id=?",array($getid));
$row=$result->fetch();
//To get paste column of that id
$paste=$row->paste;
echo $paste;
I am using PDO connection and a foreach loop to fetch data and display them into a form in order to allow a user to see the entered data. in the PHP code below I do use prepared statement to attempt to retrieve the data
here is the php code
<?php
/**
* Simple wrapper around htmlspecialchars() that always passes the correct require options
*
* #param string $str
* #return string
*/
function html($str)
{
return htmlspecialchars($str, ENT_COMPAT | ENT_HTML5, 'utf-8');
}
error_reporting(-1);
ini_set('display_errors', 'On');
$servername = "xxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname= "xxxxx";
$charset = 'utf8';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=%s', $servername, $dbname, $charset);
try {
$dbh = new PDO($dsn, $username, $password, $options);
$sth = $dbh->prepare("SELECT id, cognome, indirizzo FROM req_table");
$rows = $sth->execute()->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
exit("Connection failed: " . $e->getMessage());
}
?>
<html>
<head>
<title>Form</title>
</head>
<body>
<form action="req.php" method="post">
<table>
<tr>
<td>Nome</td>
<td><input type="text" name="nome"/></td>
</tr>
<tr>
<td>Cognome</td>
<td>
<select name="cognome">
<?php while ($row = $rows->fetch(PDO::FETCH_ASSOC) { ?>
<option value="<?= $row['id'] ?>"><?= html($row['cognome']) ?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>Indirizzo</td>
<td>
<select name="indirizzo">
<select name="indirizzo">
<?php while ($row = $rows->fetch(PDO::FETCH_ASSOC) { ?>
<option value="<?= $row['id'] ?>"><?= html($row['indirizzo']) ?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" name="Invia" value="Submit" />
</td>
</tr>
</table>
</form>
</body>
</html>
I really hope the above code is clear enough for you to tell me what solution can be found in order to fix this problem
CODE EDIT
error inside try/catch
first edit
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
exit("Connection failed: " . $e->getMessage());
}
second edit
$rows = $sth->execute();
third edit
<?php while ($row = $rows->fetch(PDO::FETCH_ASSOC) { ?>
<option value="<?= $row['id'] ?>"><?= html($row['cognome']) ?></option>
<?php } ?>
and now 500 server error and a blank page
PS error reporting is enabled and I have replaced foreach with while loop
Any time you get the...
"Fatal error: Call to a member function..."
...it is likely because there is an issue with your query. The prepare() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!
First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:
error_reporting(E_ALL);
ini_set('display_errors', 1);
If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.
Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
The error is generic and not very helpful to you in solving what is going on.
With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
// any additional code you need would go here.
} else {
$error = $mysqli->errno . ' ' . $mysqli->error;
echo $error; // 1054 Unknown column 'foo' in 'field list'
}
If something is wrong you can spit out an error message which takes you directly to the issue. In this case there is no foo column in the table, solving the problem is trivial.
If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.
You forgot to use execute()
Try this:
$rows = $sth->execute()->fetchAll(PDO::FETCH_ASSOC);
Nevertheless, using fetchAll() in order to use a foreach() loop after that is useless. So replace this:
$rows = $sth->execute()->fetchAll(PDO::FETCH_ASSOC);
by this:
$rows = $sth->execute();
and within your HTML, replace this:
<?php
foreach ($rows as $row) { ?>
<option value="<?= $row['id'] ?>"><?= html($row['cognome']) ?></option>
<?php } ?>
by this:
<?php
while($row = $rows->fetch(PDO::FETCH_ASSOC) { ?>
<option value="<?= $row['id'] ?>"><?= html($row['cognome']) ?></option>
<?php }?>
I am starting to use PDO and I successfully connected to MySQL using PDO. However, when I try to SELECT stuff from my DB, nothing happens. Nothing is echoed. (even though I have records in that table, and the column username exists) No error in my PHP log.
I am using MAMP and all PDO components seem to be working in phpinfo() (since I was able to connect to db in the first place)
Please let me know what could have gone wrong. Thanks a lot
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
$stmt=$connection->prepare("SELECT * FROM users");
$stmt->execute();
while ($row=$stmt->fetch(PDO::FETCH_OBJ)){
echo $row->username;
}
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>
You need to tell PDO that you want it to throw exceptions:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Following your comment below, it is apparent that your DSN is incorrect. It should be:
$connection = new PDO('mysql:host=localhost;dbname=my_db','my_username','xxxxxxx');
Note that the syntax is dbname= rather than dbname: (which you had originally).
First, get your query out of your PDO connection segment...
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>
Then, do it.
<?php
$SQL = 'SELECT * FROM users';
foreach($connection->query($SQL) as $row){
print $row['username'] . "\n".'<br />';
}
?>
Why not ask PHP?
catch(Exception $e)
{
die($e);
}
Looks like your either don't have data in that table or have an error:
Try to add this code after $stmt->execute();:
$arr = $sth->errorInfo();
print_r($arr);
Can anyone spot where I might be going wrong with the following code?
<?php
//MySQL Database Connect
require 'config.php';
$unitFrom = "kilogram";
$unitTo = "gram";
$units = "9000";
try{
require 'config.php';
$stmt = $dbh->prepare('CALL sp_get_conversion(:in_unit_from, :in_unit_to, :in_amount, #out_amount)');
$stmt->bindParam(':in_unit_from',$unitFrom,PDO::PARAM_STR,4000);
$stmt->bindParam(':in_unit_to',$unitTo,PDO::PARAM_STR,4000);
$stmt->bindParam(':in_amount',$units,PDO::PARAM_STR,4000);
$stmt->execute();
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
$conversion = $dbh->query( "SELECT #out_amount" )->fetchColumn();
echo $conversion;
}
?>
When I run the stored procedure in phpmyadmin it works fine but nothing is echoed out when I try the code above.
Thanks
The following should be in the try block:
$conversion = $dbh->query( "SELECT #out_amount" )->fetchColumn();
echo $conversion;
You currently have it in the catch block so it will get executed only if there is an exception is generated.
Try handling your error as dictated here. It's how I've always worked with PDO issues.