Resolving MySQLi Error due to Incorrect Usage of MySQL Variable

After a long time of receiving help, I have finally created my account here. However, this time I couldn't find an answer to my question.

I am new to MySqli and I am currently attempting to run a script that previously worked in phpMyAdmin.

The issue arises when I try to utilize a 'mysql variable'. Below is the code and the error message:

$consulta = "SET @var= (SELECT ticket_id FROM ost_ticket WHERE number = 410037);

SELECT DISTINCT a.number, a.created, b.address, 
SELECT DISTINCT title FROM ost_ticket_thread a WHERE a.ticket_id = @var AND a.source LIKE  'API')title, 
SELECT DISTINCT body FROM ost_ticket_thread a WHERE a.ticket_id = @var AND a.source LIKE  'API')body,
d.state, 
c.body resposta
FROM ost_ticket a
LEFT JOIN ost_user_email b ON b.user_id = a.user_id
LEFT JOIN ost_ticket_thread c ON c.ticket_id = a.ticket_id
LEFT JOIN ost_ticket_status d ON d.id = a.status_id
WHERE a.ticket_id = @var AND c.id = (SELECT MAX( a.id ) FROM ost_ticket_thread a WHERE a.ticket_id = @var ) ";


$resultado = $MySQLi->query($consulta) OR trigger_error($MySQLi->error, E_USER_ERROR);

$cont = 0;

while ($informacao = $resultado->fetch_object()) {


$data[$cont] = array(
'numprot'      =>      $informacao->number,
'email'     =>      $informacao->address,
'assunto'     =>      $informacao->title,
'status'     =>      $informacao->state,
'body'     =>      $informacao->body,
'resposta'     =>      $informacao->resposta,
'dtcriacao'     =>      $informacao->created,
);

$cont++;

}

echo "{'lista':".json_encode($data)."}";

Even though it worked perfectly fine in phpMyAdmin, I encountered the following error when using the mysqli query function:

Fatal error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT distinct a.number,a.created,b.address, (select distinct title from ost_t' at line 3 in /home/u605553750/public_html/JSONResposta.php on line 22

The issue is found on line 22 which corresponds to:

 $resultado = $MySQLi->query($consulta) OR trigger_error($MySQLi->error, E_USER_ERROR);

I am seeking guidance regarding the correct way to execute this script using MySqli.

Thank you,

Bruno

Answer №1

Looks like you overlooked including the 'from' clause in that line.

SELECT DISTINCT a.number,a.created,b.address [FROM YOURTABLE]<-add this, (... 

Upon further clarification, it seems that I now have a better understanding of your intention. In that case, ensure that your subqueries return a select_expression. Do you notice the use of "AS"?

SELECT DISTINCT a.number,a.created,b.address,
(SELECT DISTINCT title FROM ost_ticket_thread a WHERE a.ticket_id = @var AND a.source LIKE 'API') AS title

http://dev.mysql.com/doc/refman/5.7/en/select.html

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

Should JSON APIs be expected to return strings or JavaScript Objects?

Suppose I request subscriber data from Mailchimp, and they respond with an http request containing JSON in the body. Should I be able to access it like this: var thingy = body.property; Or do I need to do it this way: var object = JSON.parse(body); var ...

Building a Dynamic Web App with PHP and Vue.js

I developed an API using PHP and you can access it through this link: However, I encountered an issue when trying to display the data on the front-end of my Vue.js (Home.vue) file using axios. Below is the code I used: <ul class="ta-track-list" v-if= ...

Retrieve the authentication token from the JSON response in order to proceed to the next task

* The following code snippet shows the implementation of the onPostExecute() method: @Override protected void onPostExecute(String s) { if (s != null) { s.replaceAll("\\s+",""); Log.e("Fetch_fr ...

Working with PHP to retrieve values from an array object

I have the following array: businesscommercialArray = { 40E: { id: 94, swift_code: "40E", status: 1 }, 43P: { id: 106, swift_code: "43P", status: 2, note: "Allowed (INSTEAD OF EXIST ...

Tips for Deserializing Complex JSON Objects in C#:

I have the ability to deserialize JSON and insert data into a database table, but I am struggling with inserting the correct "ParentID & ParentFullPath" within the table. Is there a way to achieve this using recursion or without recursion? Here is the met ...

Creating an event listener that can detect changes to a specific field before or during a save action

I am facing a challenge in updating specific fields during a save operation, but only when one particular field is being modified. I'm unsure of how to achieve this. Additional information: If a user is editing the 'is_activated' field in m ...

Verifying the current password and updating the hashed password

I have been struggling with creating a PHP script for updating user hashed passwords. Unfortunately, the script is not functioning as expected and no error messages are being displayed. Every time, it only shows "Your old password is incorrect" message. I ...

Utilizing Javascript to Extract Data from Twitter Json Files

Can someone provide assistance with parsing JSON feed text retrieved from Twitter? I am looking to access and apply style tags to elements like the link, created date, and other information. Any tips on how I can achieve this task successfully would be g ...

Merging PHP Webservice with C# Client for Enhanced Functionality

In my C#/Winforms application, I am using PHP webservices. One PHP webservice called uploadFile.php is responsible for uploading a blob file (e.g., by a unix application) to a MySQL database. Another webservice, getFile.php, is used to retrieve the file if ...

Struggling to transfer information from a JSON document to a MYSQL database using PHP, however, it seems the data isn't aligning with the required format

Currently facing an issue with inserting JSON data into MYSQL database using PHP. The data is not aligning properly with the codes written. Extracted raw data from a transportation website: "d": [ { "CreateDate": "/Date(1465439077603)/", ...

Changing the content of a JSON save file in ASP.NET: A step-by-step guide

I have successfully bound data from a database to a JSON file using code in the code-behind file. string JSONString = JsonConvert.SerializeObject(datatable); The default format for storing a data table in a JSON file is as shown below: [ { "Produc ...

What steps should I take to retrieve JSON data using fetch from my Express server?

After several attempts to use fetch for retrieving JSON data from my express server, I have encountered some issues. While the fetch function works well with JSONPlaceholder, it seems to fail when accessing my express code. Below is the snippet of my fetc ...

Optimizing PHP code for improved efficiency and professionalism

Working on a PHP assignment, I have everything working but the code looks too simple. It calculates total pay based on entered hours and wages. Any suggestions to make it better, shorter, and more efficient? <?php $hours = $_GET ["hours"]; $wages = $_ ...

Retrieving information from a MySQL database and populating it into cells using

So, I have a PHP script that is working fine, but I need to make some modifications. Here's the current script: <?php $db_host = '127.0.0.1'; $db_user = 'root'; $db_pwd = ''; $database = 'hit'; $table = &ap ...

Converting an object with a System.Drawing.Image into a json format

I'm facing a bit of a challenge and struggling to find a solution... Within my interface (and implemented class), there is an image property... Guid uid { get; set; } Image imageData1 { get; set; } string fileName { get; set; } The imag ...

Pass the search query and a specific flag to a PHP function using the Ajax method

I need help figuring out how to filter autocomplete results based on a custom flag being sent to the function along with the search term. This would allow users to specify additional criteria, like finding cities with a stadium or swimming pool. var filt ...

The Jetty server is unable to provide JSON responses

Whenever I use the command mvn jetty:run to initiate my server, it fails to return JSON formatted strings. Instead, it only returns raw strings or "null" for all objects. In the code snippet for my endpoint, you can observe that there is no variation in r ...

insert a distinct value into a specific location within a JSON file using python

I am working on updating a JSON file by adding a new key-value pair. current json: [{'Name': 'AMAZON', 'Type': 'Web', 'eventTimeEpoch': 1611667194}] The goal is to add a location parameter and set its ...

Unlocking the Magic of JSONP: A Comprehensive Guide

Currently attempting to utilize JSONP in order to work around Cross Domain challenges. I referenced this solution: Basic example of using .ajax() with JSONP? $.getJSON("http://example.com/something.json?callback=?", function(result){ //response data a ...

What is the best approach to determine the numerical equivalents of options in a dropdown menu using PHP and JS

Hey guys, I'm really stuck on this problem and I can't seem to find a helpful tutorial anywhere. I've got a form with two drop-down menus, each with a "value" attribute. What I want is for users to be able to select an item from both drop-do ...