Query multiple table in one tooltips, order form - php

I'm trying to code a tooltip, which uses http://craigsworks.com/projects/simpletip/# simpletip plugin, which returns data via ajax. However, i can't seem to display the data from 3 tables, which is fetched via the data image, as each image is assigned to it's own id. as seen below, i need to display all data from the table, but with 3 tables to read from. in my webpage, a php statement will query data from one table for each category, generated by this tooltips. only a round tooltip came out, not even mysql_error(). i need help asap. this is the only site where i seem to get inputs from others.
<?php
define('INCLUDE_CHECK', 1);
require "../connect.php";
if (!$_POST['img'])
die(mysql_error());
$img = mysql_real_escape_string(end(explode('/', $_POST['img'])));
$row = mysql_fetch_assoc(mysql_query("SELECT alcoholic.*, non_alcoholic.*,
non_alcoholic1.* FROM alcoholic INNER JOIN non_alcoholic USING (img) INNER JOIN
non_alcoholic1 USING (img) WHERE img='" . $img . "' "));
if (!$row)
die(mysql_error());
echo '<strong>' . $row['name'] . '</strong>
<p class="descr">' . $row['description'] . '</p>
<strong>price: $' . $row['price'] . '</strong>
<small>Drag it to your shopping<br /> cart to purchase it</small>';
?>

I'm guessing there are three tables with an img column? If so, is this what you need?:
SELECT
alcoholic.*, non_alcoholic.*, non_alcoholic1.*
FROM
alcoholic
INNER JOIN non_alcoholic USING (img)
INNER JOIN non_alcoholic1 USING (img)
WHERE
img = '" . $img . "'
Edit: When I said update your OP with the new issue I didn't mean overwrite it, I meant add it underneath so that this answer (and others if there were any) make sense.
Anyway, the problem is that $row['name'], etc. don't refer to anything in the SELECT statement. You need to change alcoholic.*, non_alcoholic.*, non_alcoholic1.* to what it is you're pulling out, for example:
SELECT alcoholic.name, alcoholic.description, alcoholic.price ...

Related

Get record from 2 tables using PHP returning multiple results

I have 2 tables. One called local_requestors and one called local_aid. They both have different sets of data, but they both share a column, the column in local_requestors called suser_scheme is the same as the data in the local_aid table column called scheme_id.
I want to query my tables to get all data from the local_requestors table, where the ID matches that of the row in the local_aid table.
I've used the following...
$stmt = $conn->prepare('SELECT *
FROM local_requestors
INNER JOIN local_aid
WHERE local_requestors.user_scheme=local_aid.scheme_id
AND local_requestors.id = :aid_id');
$stmt->execute(['aid_id' => $user_id]);
while($row = $stmt->fetch()) {
echo '<p>' . $row['user_name'] . '</p>';
}
This is all on a local page that I can only access, but to query the table I post some $_GET[] variables...
$user_id = $_GET['id'];
$scheme_id = $_GET['scheme_id'];
No matter what I try, I keep getting the same row from the local_requestors table, repeated around 10 times.
My goal is to get print the name of the user in the record from local_aid and a number of related records from local_requstors.
echo 'Hello ' . $aid_name . ', there is ' . $rowCount . ' people that need help in your area.;
I think you may have ment
SELECT *
FROM local_requestors
INNER JOIN local_aid ON local_requestors.user_scheme=local_aid.scheme_id
WHERE local_requestors.id = :aid_id
And from your description of what you want you may want a LEFT JOIN instead of a INNER JOIN

MySQL fastest way to query rows

My problem is that i don't yet have a good server to test this on but i'd like to know if it faster to use:
$sqlgetg = "SELECT assignments.id FROM assignments LEFT JOIN userassignments ON assignments.id = userassignments.assignmentid WHERE userassignments.userid = '" . $row['id'] . "' AND userassignments.assignmentid = '" . $assignmentid . "'";
or
$sqlgetg = "SELECT NULL FROM assignments LEFT JOIN userassignments ON assignments.id = userassignments.assignmentid WHERE userassignments.userid = '" . $row['id'] . "' AND userassignments.assignmentid = '" . $assignmentid . "'";
Since i have to check if there even is an assigment for the user with assignment id of x? I don't need anything else but this: if(mysqli_num_rows($resultgetg) > 0)? In both cases phpMyAdmin gave me the row number that i wanted. (I checked it with
without WHERE and it still worked.)
EDIT:
I don't know how and why NULL works but it does...
You can select any static value "from" a table if you just want to count the rows returned... SELECT NULL or SELECT 42 or whatever. But both of your strategies are in fact suboptimal, because they require unnecessary work by the server and unnecessary network traffic and unnecessary handling of the result set that you are only planning to discard.
If counting rows is what you want, then actually do that. you should SELECT COUNT(*) AS how_many_rows ... and let the server count the rows and return a single row with a single column ("how_many_rows" -- make up your own alias) containing the count.

How to sort and display database results with MySQL/PHP

I am using PHP to sort items on my website into different locations/different divs. I have a script in each div where I want the results to be displayed So if there are 4 divs there are 4 scripts. (4 categories) Each script has a query in the head of my page.
MySQL query for category/div 1
$sql_category1 = <<<SQL
SELECT *
FROM `list_items`
WHERE `category` = 1
ORDER BY `rating` ASC;
SQL;
if(!$category1 = $db->query($sql_category1 )){
die('There was an error running the query [' . $db->error . ']');
}
My PHP for category/div 1:
<?php
while($row = $category1->fetch_assoc()) {
'<div class="list-item-container">'
. '<img title="' . $row['title'] . '" class="favicon" src="http://www.google.com/s2/favicons?domain='. $row['fav_url'] . '" />'
. '</div>';
}
?>
My goal: When i am entering data into the table and there are two items that can be classified as two different things, so two different categories, I have to make two copies of it. This way a item will appear in both categories. Same item two different categories. I give one of the items a category value of 1 and the other item a category value of 2.
Rather than making two separate entries of the same item is there a way that I can give that item two separate category values? This way the item will appear in both categories when my scripts run and sort them.
I tried 1,2 1:2 and 1;2 as the value of the item. Tho im sure it's not even close to that.
Thanks in advance!
make 3 tables:
category (id, name, ...)
item (id, name, ...)
item_category (id_item, id_category)
them make join of them in your queries, e.g. your first query will become
SELECT *
FROM `list_items` t,`item-category`
WHERE `id_category` = 1
and `id_item` = t.`id`
ORDER BY `rating` ASC;
After you have connection table you can put in it whatever connections you want

MySQLi query skipping first 5 rows

I have the following MySqli query:
$run = 0;
$result = $conn->query("SELECT title, author,i.isbn13, i.sku, quantity, weight, listed_price
from book
LEFT JOIN inventory i on book.isbn13 = i.isbn13
where quantity > 0 and i.isbn13 like '978%' limit $run, 5");
Which I then run through Amazon's API to return XML Data. I then parse that to update my table with:
$conn->query("update book set author = '" . addslashes($amazonResult['Author']) . "', title ='" . addslashes($amazonResult['Title']) . "',
edition='" . addslashes($amazonResult['Edition']) . "',
weight='" . $amazonResult['Weight'] . "', publisher='" . addslashes($amazonResult['Publisher']) . "', binding='" . $amazonResult['Binding'] . "',
pub_date='" . $amazonResult['PublishDate'] . "', listed_price = '" .$amazonResult['ListPrice'] . "'
where isbn13 = '" . $amazonResult['isbn'] . "'");
Update $run:
$run=$run+5;
and have it loop through again. Yet my output skips the first 5 rows in the table and returns the next 5. Also, after running about 20 or so records, it skips 5 again. The rows that it processes, it does correctly, which I verify by an echo of the query. When I use the query in Navicat, replace $run with 0, everything looks fine, the first 5 rows are returned.
Any idea what I did wrong or how I can fix this? I have never encountered this in the past and use almost the same query for different reports.
If you want to return a specific range of records, make sure to also add an order by clause. MySQL might change the order of rows between queries.
Another, maybe even more plausible cause, is that a query can sometimes fail. For instance, if one of the fields contains an invalid character, it might break your query, return false instead of a mysqli query result, and therefor fail to output anything.
You are using addslashes to escape strings, but that's not the proper way to do it. You can use mysqli_real_escape_string, or even better: use parameterized queries (prepared statements).

Displaying info from MySQL - from 2 different tables... Argh! Noob in trouble

I am trying to pull some stats from a gameserver database, and return them in a table.
I have managed to do the first bit - pulling 10 results, displaying in a table in html, HOWEVER... the next bit has me stumped... I for each player I want to get some info from another table...
Here is what I have so far... excuse the messy code, I am just learning!
// adding ALL info from the first 10 tables 'profile' based on humanity, ascending, to the variable 'profile_info'
$profile_info = mysql_query("SELECT * FROM profile ORDER BY humanity desc LIMIT 10");
while($row = mysql_fetch_array($profile_info))
{
// Below I add the players unique ID into the variable $unique, to be used later for pulling their survival time from the 2nd table, which is called 'survivor'
$unique = $row['unique_id'];
echo "<tr>";
echo "<td class=\"c1\">" . $row['name'] . "</td>";
echo "<td class=\"c2\">" . $row['humanity'] . "</td>";
echo "<td class=\"c3\">" . $row['total_survivor_kills'] . "</td>";
echo "<td class=\"c4\">" . $row['total_bandit_kills'] . "</td>";
echo "<td class=\"c5\">" . $row['total_zombie_kills'] . "</td>";
echo "<td class=\"c6\">" . $unique . "</td>";
//In the line below, I try to get data from the 2nd table (called survivor), checking for the unique_id for the player (extracted from the first table, called 'profile') which is common across both tables and which have a 0 in the field 'is_dead'
$result = mysql_query("SELECT * FROM `survivor` WHERE `unique_id` ='.$unique' AND `is_dead` = 0") or die(mysql_error());
echo $unique;
if (mysql_num_rows($result)) {
$survivors_survival_time = mysql_fetch_assoc($result);
echo "<td class=\"c7\">" . $survivors_survival_time['survival_time'] . "</td>";
}
I hope that, even though the code above is probably rubbish, you can see what I am trying to do?
Most of it works fine, it is just that the part where I try to get the info for a player from the second table, based on their unique_id from their row in the first table, it doesn't work :(
Any ideas, or is the above so bad I should just give up?
I believe you have a typo in your query that pulls info for each individual player here:
mysql_query("SELECT * FROM `survivor` WHERE `unique_id` ='.$unique' AND `is_dead` = 0")
Specifically, the unique_id = '.$unique' part, where there is an extra . in the value field.
Try removing it to get the following:
$result = mysql_query("SELECT * FROM `survivor` WHERE `unique_id`='$unique' AND `is_dead` = 0") or die(mysql_error());
This, of course, is under the assumption that you don't prepend a . to each of your unique_id values in the survivor table.
Side-note (not answer specific):
If you were to update your code to use the MySQLi or PDO libraries opposed to the deprecated mysql_ functions, you would have the ability to use prepared statements. Using these would prevent minor errors like the one noted above as well as provide more-secure code too.
Nest your while loops or read about mysql LEFT JOIN and update your query.
I do not know about MySQL, because I've always used MSSQL, but here's how I would write it in PHP and mssql:
'SELECT * FROM survivor WHERE unique_id="'.$unique.'" AND is_dead = 0'
Try it and let me know ;)
You can combine those queries using a join:
SELECT
*
FROM
profile AS p
LEFT JOIN
survivor AS s ON p.unique_id = s.unique_id
WHERE
s.is_dead = 0
ORDER BY
humanity DESC
LIMIT
10
Then simply loop the results. Using LEFT JOIN gives you all the results from profile and any matches in survivor. If you change that to JOIN (i.e. drop the LEFT) it will give you only rows where a match exists in profile AND survivor.
A couple of suggestions:
Explicitly state which columns you want, i.e. "SELECT name, humanity, survival_time, etc..." instead of SELECT *.
Use a query method that allows you to use prepared statements, such as PDO.
Use single quotes instead of doubles so that you don't have to escape all the doubles in your HTML output. Anyone else who reads your code will thank you for that!

Categories