PHP script to search mysql database doesn't return result - php

Following the code I wrote. This doesn't return any values, even though the table has the keywords.
<?php
$conn = mysql_connect("localhost", "root", "qwerty");
mysql_select_db("mis", $conn);
$coursename=$_POST['coursename'];
$sql = "SELECT *
FROM course
WHERE coursename='$coursename'".
"ORDER BY coursename";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
echo $row['coursename'];
};
?>

The problem is case-sensitivity. MySQL identifiers are not case sensitive unless you enclose them in backticks. However, PHP array indexes are.
Therefore if you have a column named CourseName, the following query will work:
SELECT *
FROM course
WHERE cOuRSEnaME = 'foo'
ORDER BY courSEnAmE
But, referencing it in PHP as $row['coursename'], $row['cOURsENamE'] or any other differing combination will not work, as these all refer to different keys. You must use $row['CourseName'].
See also: PHP array, Are array indexes case sensitive?

Try to add error_reporting(E_ALL); immediately after your <?php and see if you get any error messages from your browser.
You should be able to track down the root cause of your problem.
Good luck with your coursework (i guess ;).

$sql = "SELECT *
FROM course
WHERE coursename='$coursename'".
"ORDER BY coursename";
Your code is good but it is much better to use concatenate the string and the variable so it is easily interpreted and also I wanna point out that there is no space before your ORDER BY statement that can cause an error, so make sure there are spaces between them coursename = '" . $coursename . "' ORDER BY. See the full query below
$sql = "SELECT *
FROM course
WHERE
coursename = '" . $coursename . "' ORDER BY coursename";

$sql = "SELECT *
FROM course
WHERE coursename='" . $coursename . "'
ORDER BY coursename";
$result = mysql_query($sql, $conn);
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
echo $row['coursename'];
}
} else {
echo "given coursename does not exist";
}
?>

Related

Another beginner with a mysqli issue

I'm quite new to working with PHP and databases. So, like all beginners, I'm having problems with the mysqli extension. I was trying to avoid using mysqli_results, as I didn't want to deal with an array and a loop every time I want a simple piece of data. But that might not be possible.
I need to echo $user_count, but nothing seems to be stored there. My code seems to be okay according to the API, but maybe I'm just trying to use the wrong functions altogether. How do I put the result I need into $user_name?
mysqli_query($conn, "SELECT * FROM `wp_users` WHERE 1");
$result_user_count = mysqli_query($conn, "SELECT COUNT(`ID`) FROM `wp_users`");
$user_count = mysqli_fetch_field_direct($result_user_count, 0);
echo $user_count . ' users found on ' . $dbname . ':</br>';
Based on your provided code, you need to change it like below:-
$query = mysqli_query($conn, "SELECT COUNT(ID) AS COUNT FROM wp_users") or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($query)) {
echo "Total Users Are:- ". $row["COUNT"];
}
Note:- try to add mysqli error reporting code so that you will what problem actually exist in your query code, and you can easily resolve them. thanks
Try this. comment if not worked.
$query = mysqli_query($conn, "SELECT COUNT(ID) AS COUNT FROM wp_users");
if ($u_count = $mysqli->query($query)) {
while ($res = $u_count->fetch_assoc()) {
echo "Total Users: ". $res["COUNT"];
}
}

Print sql query on localhost

I have a SQL query in my PHP file that makes use of some variables in it. I want to print the query itself on the localhost to check as to whether the entire query is been executed or not.
My query is like this:
$result = mysql_query("SELECT * FROM sample WHERE col01 LIKE '%$abc%',$db);
I am trying to print the query using echo $result but get Resource id #25 on localhost. I want to print Select * FROM ... as the output. Is there any way?
First of all: You are missing a double quote: $result = mysql_query("SELECT * FROM sample WHERE col01 LIKE '%$abc%'",$db).
That said, what stops you from
$sql="SELECT * FROM sample WHERE col01 LIKE '%$abc%'";
$result = mysql_query($sql,$db);
echo $sql;
If you were using PDO (and you should, the old mysql_ functions are deprecated and insecure) you could just use PDOStatement->queryString property to view the query at a later time.
Store as a variable $sql
Its normal, first you need to fetch that resource obj
And anyway you missing a double quote,
example.
$sql = "SELECT * FROM sample WHERE col01 LIKE '%$abc%'";
$result = mysql_query($sql);
while ($line = mysql_fetch_object($result)) {
echo $line->colname ."\n";
}
echo "\n" . ' query: ' . $sql
And from PHP 5.5.0 and beyond use mysqli
$sql = "SELECT * FROM sample WHERE col01 LIKE '%$abc%'";
if ($result = $mysqliobj->query($sql)) {
while($line= $result->fetch_object()){
echo = $line->colname ."\n";
}
}
echo "\n" . ' query: ' . $sql
or print_r($mysqliobj->info); # store las query

What is an SQL query for counting records that are existing more than once in a database?

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("students");
$id = $_POST['id'];
$grade = $_POST['grade'];
$query = "INSERT INTO `st_table` (`St_id`,`Grade`) VALUES ('$id','$grade')";
$result = mysql_query($query);
$query = "SELECT * from `st_table`";
$result = mysql_query($query);
echo "<table>";
echo "<th>St_id</th><th>Grade</th>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['St_id'] . "</td><td>" . $row['Grade'] . "</td></tr>";
}
This code adds values into a table both ID and Grade. I want another query that will be able to count how many As, Bs, Cs, etc. and OUTPUT it on an html table.
Here, Your query is ok just group by Grade not Grades
"SELECT `Grade`, COUNT(*) AS count FROM `st_table` GROUP BY `Grade`";
Here is sqlfiddle
After edit
The query i am mentioning should work for you, you can check fiddle for that as for as you modified code is concerned you have to change your table a bit since you are going to include St_id as well so make it 3 column and correspondingly change query too.

mysql query works with plain text, but not with variable

I am trying to print out some topic information, but it is not going so well. This is my query:
SELECT * FROM topics WHERE id='$read'
This doesn't work. I've echo'ed the $read variable, it says 1. So then if I do like this:
SELECT * FROM topics WHERE id='1'
It works perfectly. I don't get what is the problem. There's no hidden characters in $read or anything else like that.
Try like this:
$query = "SELECT * FROM topics WHERE id='" . $read . "'"
ID is normally a numeric field, it should be
$id = 1;
$query = "SELECT * FROM topics1 WHERE id = {id}"
If you are using strings for some reason, fire a query like
$id = '1';
$query = "SELECT * FROM topics1 WHERE id = '{$id}'"
SELECT * FROM topics WHERE id=$read
it consider it as string if you put i single quotes
I wonder why all the participants didn't read the question that clearly says that query with quotes
SELECT * FROM topics WHERE id='1'
works all right.
As for the question itself, it's likely some typo. Probably in some other code, not directly connected to $read variable
try
$query = sprintf("SELECT * FROM topics WHERE id='%s';",$read);
Also remember to escape the variable if needed.
Looks like you might have an issue with the query generation as everyone else is pointing to as well. As Akash pointed out it's always good to build your query in to a string first and then feed that string to the MySQL API. This gives you easy access to handy debugging techniques. If you are still having problems try this.
$id = 1;
$query = "SELECT * FROM `topics1` WHERE `id`={$id}";
echo ": Attempting Query -> {$query}<br />";
$res = mysql_query($query, $dblink);
if($res <= 0)
die("The query failed!<br />" . mysql_error($dblink) . "<br />");
$cnt = mysql_num_rows($res);
if($cnt <= 0)
{
$query = "SELECT `id` FROM `topics1`";
echo "No records where found? Make sure this id exists...<br />{$query}<br /><br />";
$res = mysql_query($query, $dblink);
if($res <= 0)
die("The id listing query failed!<br />" . mysql_error($dblink) . "<br />");
while($row = mysql_fetch_assoc($res))
echo "ID: " . $row['id'] . "<br />";
}
This will at least let you monitor between calls, see what your query actually looks like, what mysql says about it and if all else fails make sure that the ID you are looking for actually exists.
try with this : SELECT * FROM topics WHERE id=$read

How to ignore duplicate rows when echoing mysql query result

I trying to make tag cloud system and i enter the tags in one table with "name" and "product_id".
I make that may have multiple same tags everyone for different product.
My problem is that when echo the tags from the table it show me all tags,this is good,but the repeated tags are in that count. I need to echo repeated tags only once, but i don't know how to make that.
Here is and my code that showed and repeated tags.
$id = $_GET['catid'];
$sql = "SELECT * FROM tags_group";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
//echo $row['name'];
$id = $row['id'];
$sql1 = "SELECT * FROM tags WHERE tag_group='$id'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_array($result1)) {
$name = $row1['tag_name'];
$sql2 = "SELECT * FROM tags WHERE tag_name='$name'";
$resut2 = mysql_query($sql2);
$rows = mysql_num_rows($resut2);
echo $row1['tag_name'] . '(' . $rows . ')' . '<br>';
// echo $row1['tag_name'].$rows.'<br>';
}
echo '<br>';
}
You have to use the DISTINCT keyword do avoid duplicates:
SELECT DISTINCT * FROM tags_group
As I mentioned in the comments above, you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article.
UPDATE
It also looks like you're using nested queries, rather than joining your tables and retrieving the results. Try this instead:
$id = $_GET['catid'];
$sql = "SELECT tags.tag_name, count(*) AS name_count FROM tags
INNER JOIN tags_group
ON tags.tag_group = tags_group.id
GROUP BY tag_name";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$name = $row['tag_name'];
$rows = $row['name_count'];
echo $name . '(' . $rows . ')' . '<br>';
// echo $row['tag_name'].$rows.'<br>';
}
echo '<br>';
Here I don't use DISTINCT but GROUP BY allows you to aggregate the count for each distinct row (based on the GROUP BY column).
Take a look at this diagram to better understand how joins work.

Categories