PHP results not displaying and no error message to go by - php

A self taught newbie here looking for advice...
I have very simple PHP query against a MySQL database that is suppose to generate a drop down menu populated with information from the MySQL database. I was wondering if based on the code included in this posting someone could steer me in the right direction or lend a suggestion as to what I should.
P.s. the MySQL database is products the table I am selecting from within is products and the column I am trying to select is description.
<?php
$adConn = mysqli_connect("localhost", "user", "password", "products");
$result = "SELECT * FROM products where Description order by descending";
$result = mysqli_query($adConn, $result);
echo "<select name='product'>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['Description'] . "'>" . $row['Description'] . "</option>";
}
echo "</select>";
?>

Your where condition is not correct. Also look for order by.
Try this :
$result = "SELECT * FROM products where Description = 'SOME VALUE' order by SOME FIELD desc;
Refer this : http://dev.mysql.com/doc/refman/5.7/en/select.html
Also you are mixing mysqli_* and mysql_*.
Please don't use mysql_* it is deprecated and removed from PHP 7.
For mysqli : http://php.net/manual/en/book.mysqli.php

If you're only looking for the descriptions from your products table, you can change your select statement to something like this:
SELECT description
FROM products
ORDER BY <column name> desc;
This will give you all the descriptions on your products table, in descending order based on a column name. Not sure what you are trying to order by on the products table, but you need to add a column name to your ORDER BY clause.
Note - You had description in your WHERE clause, so if you are looking for a specific description, you could do something like this instead:
SELECT description
FROM products
WHERE description = 'some specific description';
Returns one specific description only, thus no need for an ORDER BY clause.

You need to learn the basic concepts of how to make a SQL statement .
Here are some basic queries you can take a look at for example:
Simple straight forward select all:
SELECT * FROM products;
Select where column value equals to something:
SELECT * FROM products WHERE product_category=foo;
Select and order by column ascending(ASC) or descending(DESC) order :
SELECT * FROM products ORDER BY product_id DESC;
now lets combine them:
SELECT * FROM products
WHERE product_category = foo
ORDER BY product_id DESC;
It is good practice to keep all SQL functions in uppercase and column names and values in lowercase making it easy to read. Also, don't use mysql_* since it's deprecated and removed from PHP 7. Instead, use mysqli_*.

I want to thank everyone for your comments and suggestions. This web community turned out to be pretty good. I am glad that there are still people on the web willing to brainstorm and help a newbie!
Have a great day!

Related

SQL need help to group my results

Hey guy im looking to display some data from my oracle DB. im looking to group it by common data/column but cant figure it out.
$stid = oci_parse($conn, " SELECT REQ.REQSTN_NO, REQ.WO_NO, REQ.COST_CENTRE_CD, REQ.ACCT_PRIME_CD, REQ.ACCT_SUBSDRY_CD, REQ.STOCK_CD
FROM TE.REQSTNREQ
WHERE REQ.DEPT_CD='ISN'");
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
echo $row['COST_CENTRE_CD']."-".$row['ACCT_PRIME_CD']."-".$row['ACCT_SUBSDRY_CD']." ".$row['WO_NO']." ".$row['REQSTN_NO']." ".$row['STOCK_CD']."<br />";
}
Im looking to create an output like this
Ive tried Group BY and SUM/COUNT but i dont know how to structure the code properly any help would be appreciated.
This is not a real database "grouping" -- it is a display issue: you want to group rows with common column values together and print each shared column value only once.
Such display issues are best left to the presentation layer of your application and best left out of the SQL/data model layer.
Nevertheless, here is a technique you can use to group common column values together and to print each value only once, using SQL.
(Since you didn't provide your data in text form, this example uses DBA_OBJECTS to illustrate the technique).
SELECT
-- Order the row_number () partitions the same way the overall query is ordered...
case when row_number() over (partition by object_type order by object_type, owner, object_name) = 1 THEN object_type ELSE NULL END object_type,
case when row_number() over (partition by object_type, owner order by object_type, owner, object_name) = 1 THEN owner ELSE NULL END owner,
object_name,
created, last_ddl_time
FROM dba_objects o
ORDER BY
-- Important to qualify columns in ORDER BY...
o.object_type, o.owner, o.object_name;
The idea is that case statements check to see if this is the first row in a new shared common value and, only if so, to print the column value. Otherwise, it prints NULL.
You would need to use an object-relational database to achieve such a result.
Edited answer:
In MySQL you can use the following function: GROUP_CONCAT:
See reference: https://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html#function_group-concat
I believe there is a similar solution in oracle. You would need to refer to the following question:
Is there any function in oracle similar to group_concat in mysql?

MySQL Select Logic

So I'm working on an assignment right now and I can't wrap my head around the logic.
I have to populate an HTML select box with a list of courses based on a qualification code where the user is not already enrolled in a course.
Here is my current code:
//Get logged in users id
$currentID = getIDForUser($_SESSION['username']);
//Get logged in users qualification code
$qualificationCode = getUserQualification($currentID);
//Get and display list of avaliable courses for qualificationCode
$query = mysql_query("");
while($row = mysql_fetch_array($query)) {
$courseName = $row['courseName'];
$courseCode = $row['courseCode'];
print("<option value='$courseCode'>$courseName</option>");
}
The layout of the database is as follows
Courses table:
Courseoccurrence table:
So, basically at this stage the combo box will populate with Multimedia & Design as well as Data Structures & Algorithms. However, if I select Multimedia and enroll in it, it will not populate the box with that course anymore.
Stop using mysql_*, it's deprecated. Go with mysqli_* or PDO instead.
Not absolutely necessary, but you might want to change your collation from latin1_swedish_ci to utf8_general_ci or you will face problems if you ever decide to put special characters in your DB.
Now, to actually address your question:
In your question you don't say what your problem is, specifically, but based on the title I assume that you know how to build everything except for the SELECT query.
So, first you want to select all the courses that the current user is enrolled in. Then, based on the result, you want to fetch all courses that are not in the list you just selected.
This can be done fairly easily with a subselect:
// Assuming $mysqli is an OOP database handle
$query = $mysqli->prepare('SELECT `courseName`, `courseCode` FROM `Courses` WHERE `courseCode` NOT IN (SELECT `courseCode` FROM `Courseoccurrence` WHERE `personID` = ?)');
$query->bind_param('i', $currentID);
$result = $query->get_result();
while($row = $result->fetch_array())
// ...
SQL Explanation:
I think SELECT, FROM, WHERE and NOT require no explanation.
IN checks whether a value is in a list like 'A' IN ('A', 'B', 'C').
And (SELECT ...) is a so-called subselect (see Subqueries), which is a simple SELECT whose result you can use in your query, and in case of it having only one column (because we only select courseCode), it can be used as an argument to IN.

Autosuggestion works too slow

I have more than 100,000 records in my books table, my database is MySQL. I am creating an autosuggestion using PHP. It is working but it is slow. I think it is because of bulk data. Is there any solution for searching data in effective manner and how can we improve speed of that searching process?
Here is my code:
<?php
$search=$_REQUET['searc'];
$qry="select book_name from books where book_name like '%$search'";
$result=mysql_query($qry);
echo "<ul>";
while($rows=mysql_fetch_array($result))
{
echo "<li>".$rows['book_name']."<li>;
}
echo "</ul>";
?>
apply indexing or you can use fulltext indexing and search
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
$search = mysql_real_escape_string($_REQUEST['searc']);
$qry = "select book_name from books where book_name like '$search%' LIMIT 10";
and an ordinary index will solve the problem... for a while
Change your query as follows. It will fetch only first 30 items. Now the speed will increase. Also You can index your table correctly for speeding
$qry="select book_name from books where book_name like '%$search' LIMIT 0 , 30";
Try executing the following code in MYSQL:
ALTER TABLE `books` ADD INDEX `book_name` (`book_name`):
This will add an index to the table, this should speed up the search.
You are searching on the suffix of the column. Indexes work with the prefix so this query requires a full table scan. To fix this you can add a column that has the original in reverse, index it, and use it for searching:
alter table books add book_name_reverse tinytext;
update books set book_name_reverse = reverse(book_name);
alter table books add index(book_name_reverse);
After that you can search efficiently with:
$search_rev=strrev($_REQUET['searc']);
$qry="select book_name from books where book_name_reverse like '$search_rev%'";
But please use PDO or MySQLi prepared statements instead of doing this. Splicing user-submitted values into queries like this makes a classic SQL injection vulnerability.

mysql php query HAVING clause

Im trying to get this query to work but i get this error:
Unknown column 'zips.city' in 'having clause'
`$query = "SELECT
zips.*
FROM
zips
HAVING
zips.city LIKE '%$city%'
AND
zips.stateabbr LIKE '%$state%'
LIMIT 1";
$result = mysql_query($query) or die (mysql_error());`
my zips table has a city column, so im not sure what the problem is, i know im accessing the database because i can run this query with no errors:
$zip1query = "SELECT
zips.*
FROM
zips
WHERE
zips.zip = '$zip'
";
any advice would be much appreciated! thanks!
The having clause doesn't mean the same thing as the where clause : when running a simple query, you should use where -- which is what you did in your second query, that works.
having is used when the condition has to be applied on the result of a group by clause.
Which means that, here, your query should be build this way :
$query = "SELECT zips.*
FROM zips
where zips.city LIKE '%$city%'
AND zips.stateabbr LIKE '%$state%'
LIMIT 1";
With that, if you still have an error about a non-existing or not-found column (at least for city and/or stateabbr), it'll be because that column doesn't exist in your table.
In this case, there is not much we can do : you'll have to check the structure of your table, to determine which columns it contains.
You can check that structure using a web-based tool like phpMyAdmin, or using an SQL instruction such as :
desc zips;
For reference, quoting MySQL's manual page for select :
The SQL standard requires that HAVING
must reference only columns in the
GROUP BY clause or columns used in
aggregate functions. ...
Do not use HAVING for items that
should be in the WHERE clause.
For example, do not write the
following:
SELECT col_name FROM tbl_name HAVING col_name > 0;
Write this instead:
SELECT col_name FROM tbl_name WHERE col_name > 0;
...
The HAVING clause can refer to
aggregate functions, which the WHERE
clause cannot
Try using WHERE instead of HAVING.
The proper way to do it is by using a WHERE clause.
$query = "SELECT
zips.*
FROM
zips
WHERE
zips.city LIKE '%$city%'
AND
zips.stateabbr LIKE '%$state%'
LIMIT 1";
HAVING is to be used when you are GROUPing, see here for an explanation
o jeez sorry guys i figured out the problem, apparently i put a space before city when i named the columns in my table. so i renamed the column and it works thanks anyway chaps! but using the where function instead of having must speed things up alot, thanks guys!

reuse of resource in another sql statement

i am using php with mySql server, pretty new to all the sql and i have a question:
i have a query:
$book_copy_user = "SELECT * FROM copy_book " .
"JOIN copy_user_own " .
"ON copy_book.copy_id = copy_user_own.copy_id " .
"WHERE copy_user_own.user_id=1";
$res1 =mysql_query($sql1) or die (mysql_error());
which returns something like
[{"copy_id":"1","book_id":"1","user_id":"1"},
{"copy_id":"2","book_id":"2","user_id":"1"},
{"copy_id":"3","book_id":"3","user_id":"1"},
{"copy_id":"4","book_id":"4","user_id":"1"}]
i would like to do 3 different select on the result with a where clause, but when trying to so it tells me that there is more the one column.
my question is:
is there a way that i can use the select result and apply select on it?
if so how can i relate to the fields of the in the select result?
please provide code samples
thanks you all you are saints :)
You can select the data into a temporary table and perform more queries on that table.
CREATE TEMPORARY TABLE temp_table SELECT ...
But I think it would be best if you posted your actual problem, it is very likely that there are much better solutions.
SELECT * FROM (SELECT * FROM copy_book JOIN copy_user_own ON copy_book.copy_id = copy_user_own.copy_id WHERE copy_user_own.user_id=1) WHERE copy_id = 4
althrough I'm not sure if it works in mysql.
No, after running select you cannot apply another on it.

Categories