Choose a record in MySQL using its unique identifier with PHP

I want to retrieve rows by their id and display the information. My table is called text and here's its structure:

BookID Type init 
Title
Author 
PublisherName
CopyrightYear

This is how I plan to access them:

text id 10

With this command, I can fetch all the details of row number 10 including:

BookID, Title, Author, PublisherName, CopyrightYear

If I run a query like this:

text id 14

I will receive all the details from row number 14 as well.

<?php
function text($id){

$query = "SELECT * FROM text WHERE BookID =" .$id ;  

$result = mysql_query($query) or die(mysql_error()); 


$row = mysql_fetch_assoc($result); 
}

?>

<?php

echo text (14) ;
?>

Answer №1

It seems like there are a few issues that need to be addressed.

  • The use of the outdated mysql_* functions is a concern. It is highly recommended to switch to mysqli
  • Your code may be susceptible to SQL injection attacks. It would be beneficial to transition to mysqli and learn how to properly implement prepared statements.
  • There appears to be inconsistency in function names, as you have named your function text but are calling displaytext
  • Lastly, ensure that your function is returning a result by adding return $row; at the end of the function to retrieve the desired output

Answer №2

When you try to execute the function displytext(), you are actually calling a different function named text().

It is important to note that the function text() does not return any value, which means the echo statement will not output anything.

Answer №3

Apologies for the delayed response, after taking another look here is a functional code snippet. Issues found:

  • No return value in your functions
  • Failure to escape the $id variable, making it vulnerable to SQL injection attacks
  • The function name mentioned previously

Hopefully this resolves the issue for you. Please find the updated code below

<?php

function fetchText($id){
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM text WHERE BookID = $id";  
$row = mysql_fetch_assoc(mysql_query($query));
return $row;
}
print_r(fetchText('1'));
?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When utilizing an iframe, the file surpasses the specified ini size

I am currently using fancy box iframe to showcase my page, containing a file upload button. However, when I click on the form submit button, I encounter the error message "File exceeds the defined ini size". Despite searching through various resources on G ...

What is the best way to incorporate multiple variables in a MySQL query when using Node.js?

I'm facing a challenge where I need to input student data into a table using the parent key as a foreign key. The parent information is included in the same JSON object, with an array of students inside it. My goal is to retrieve the parent Id from th ...

Is there a way to eliminate empty arrays from my data?

I'm dealing with this PHP code snippet. public function display_children($parent,$level){ try { $cmd = $this->connection->prepare('SELECT mem,pid from mytree where pid = ?'); $cmd->execute(array($parent)); ...

Comparing Doctrine's Data Insertion Methods: Repository vs Entity

I have come to realize the distinction between a Doctrine repository and a Doctrine entity. While attempting to carry out basic CRUD operations on a table, I mistakenly injected a default Doctrine repository into my controller without injecting an entity. ...

What is the best way to handle binary files (such as images or audio) when serving them from a RESTful API that was built using

Exploring the most effective way to deliver files or bundles of files via a RESTful API. Considering options: Base64_encode files and include in JSON response Provide file links within JSON response Priority: Private access for certain files requiring ...

What is the best way to showcase and tally the outcome of a filtering process?

I am working with some code that looks like this :- <?php $string="cari naskah dengan edisi tahun 2017"; $stopwords = array("dan", "dengan"); foreach ($stopwords as &$word) { $word = '/\b' . preg_quote($word, ...

Laravel typically adds the "php" string as a prefix to the result

Every time I attempt to send back a view from views in Laravel, it automatically includes "Php" as a prefix. The same issue arises when I try to return JSON using Ajax. For example, if I am returning an array ("data"=> "success") in a .php file, but up ...

The Express JS server has encountered a user access issue and is denying permission for localhost to disconnect

Hey there, I'm currently working on resolving a disconnect issue with my Express.js server. When using the provided code to handle disconnect, I am encountering an error stating "access denied for user in localhost." var connection; function handleD ...

Empty space under the banner in Wordpress theme Avada

I can't seem to locate the CSS class for a blank space that appears below the header on one of my pages. This space is situated between the header and "SERVICIOS 24 HORAS". Any ideas on how I can remove this mysterious gap? My website is built wit ...

A step-by-step guide to receiving Json input in a CakePhp Restful API through the PUT method

Managing data through passing IDs in URL format like /apis/view/id.json allows me to view and delete data. public function view($id) { $api = $this->Api->findById($id); $this->set(array( 'api' => $api, ...

Issues with transferring arguments between PHP and PL/SQL

Having ventured into application development with PL/SQL for the first time, I encountered some struggles in passing parameters to PHP PL/SQL. The pre-existing PL/SQL functions within the database seemed to return the expected parameters when executing the ...

Radio button triggers an ajax call once, but then fails to function

How can I troubleshoot an issue where the ajax function only works once when clicking on a radio button to change its value from 0 to 1, but not back to 0? The form contains a table with radio buttons for each record, and clicking on them triggers the aj ...

Modify the name of the file for downloading and initiate the download either upon clicking or after a specified

Can anyone assist me in finding PHP code that can change a file name by adding the current date and then initiate a download of the file with a time delay? In case the download does not start, I would like to provide an option to download the file with the ...

"Hello there, let's chat about the need for require

I have been trying to organize my files by separating them and not putting everything in the function.php file. Here is what I have done: function required_theme_files() { require_once( get_template_directory() . '/inc/customize/color.php' ); ...

Update the form action URL when a specific option is selected from the dropdown menu upon clicking the submit

I would like my form to redirect to a specific page on my website based on the selection made in the <select> tag. For instance, if '2checkout' is selected, it should go to gateways/2checkout/2checkout.php. Similarly, if 'Payza' i ...

PHP, unable to successfully deliver email messages

My website needs a contact form that collects the user's full name, email address, subject, and message. I attempted to set up the form following a tutorial, but unfortunately, my test messages are not being sent. As I am not well-versed in PHP, I am ...

Can you provide a succinct explanation of what constitutes a well-defined "landing page"?

Could someone provide a clear and concise explanation of what exactly constitutes a landing page and how it should be utilized? I'm struggling to grasp the concept. Where is the optimal placement for a landing page on a website? Is it best placed o ...

Having trouble with the dynamic form not submitting correctly using AJAX in PHP?

I am facing an issue in my code while trying to dynamically generate a form in a table and submit it. The problem is difficult for me to solve. $(document).ready(function() { $('#btnsummary').on('click', function() { ...

Calculating total group orders in Woocommerce based on specific date custom fields

I need help summarizing the total revenue for each day within a specific time period (e.g. 2020) by grouping orders based on a custom field called "pickup_date". Instead of showing revenue by individual dates, I would like to display it grouped by the "pic ...

Using PHP to ascertain the requested dataType or responseType from the client

My ajax request is fairly simple: $.post('server.php',data, function (json) {console.log(json)},'json'); I have configured jQuery to expect json data based on the dataType setting. Question: Is the dataType parameter equivalent to re ...