mySQLi query: why I have no results? - php

When I do the same query from phpMyAdmin I have results as we can see of the picture of the link:
http://i59.tinypic.com/ncd2mp.jpg
But when I do the same from php the size of the query is 0:
<?php
//Connect to Database
$con = mysqli_connect("127.0.0.1","root","","moodle2");
//Check connection
if (mysqli_connect_errno()) {
echo 'Database connection error: ' . mysqli_connect_error();
exit();
}
//Escape special characters to avoid SQL injection attacks
$namesubject="Aplicaciones Telemáticas Multimedia (Telemática)";
$namecategory="HTML CSS JS";
$namesubject=mysqli_real_escape_string($con,$namesubject);
$namecategory=mysqli_real_escape_string($con,$namecategory);
//Query the database to get the user details.
$query="SELECT id, preguntaid, nombrepregunta, textopregunta, tipopregunta, categorianum FROM mdl_eliza_preguntas WHERE categorianum = (SELECT id FROM mdl_eliza_categoria WHERE namecategoria = '".$namesubject."' AND courseid = (SELECT category FROM mdl_course WHERE fullname = '".$namecategory."')) ORDER BY id";
$userdetails = mysqli_query($con,$query);
//If no data was returned, check for any SQL errors
if (!$userdetails) {
echo 'Could not run query: ' . mysqli_error($con);
exit;
}
$size=mysqli_num_rows($userdetails);
?>
Thank you for your time.

As per your originally posted question where you've changed '".$namecategory".' to '".$namecategory."' after my answer was posted:
Change:
WHERE fullname = '".$namecategory".')) ORDER BY id";
to:
WHERE fullname = '".$namecategory."')) ORDER BY id";
You have misplaced the quote/dot.
This seems to be the most likely cause as to why your query failed.

Related

SQL Count Error

I am trying to use a count function to show me how many employees have the title "Sales"
if( !$connect)
{
die("ERROR: Cannot connect to database $db on server $server
using user name $user (".mysqli_connect_errno().
", ".mysqli_connect_error().")");
}
else
{
$userQuery = "COUNT(empID) FROM personnel WHERE jobTitle='Sales'";
$result = mysqli_query($connect, $userQuery);
if (!$result)
{
die("Could not successfully run query ($userQuery) from $db: " .
mysqli_error($connect) );
}
if (mysqli_num_rows($result) == 0)
{
print("No records found with query $userQuery");
}
else
{
print("<h1>SALES STAFF REPORT</h1>");
while ($row = mysqli_fetch_assoc($result))
{
print("<p>There are
".$row['COUNT(empID)']."</p>");
}
}
mysqli_close($connect); // close the connection
}
?>
I am getting this 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 'COUNT(empID) FROM personnel WHERE jobTitle='Sales'' at line 1
on this line:
$userQuery = "COUNT(empID) FROM personnel WHERE jobTitle='Sales'";
I am unsure of what I am doing incorrectly, but any help would be appreciated.
End result should read "There are 4 sales staff".
My professor did include this in the assignment, not sure if that will help.
"There are two different MySQL functions that you can use here: you can
modify the SELECT statement to use a MySQL aggregation function,
or you can use the MySQL function that returns the number of records in the
result set. "
You are missing the SELECT keyword when making the statement.
You have:
$userQuery = "COUNT(empID) FROM personnel WHERE jobTitle='Sales'";
It should be:
$userQuery = "SELECT COUNT(empID) FROM personnel WHERE jobTitle='Sales'";

Display Bids from database in order

Ive been trying to display a "bid" from the database to no success.
here is my error
Fatal error: Function name must be a string in /home/rslistc1/public_html/get-bids.php on line 7
here is my code
<?php
include('session.php');
?>
<?php
require_once('mysql_connect.php');
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
$result3 = mysql_query($query3) OR die($mysql_error());
$num = mysql_num_rows($result3);
while ($row = mysql_fetch_array($result3, MYSQL_ASSOC)) { ?>
<?php echo''.$row['bid'].'';
}
?>
Any idea
Before we address the line 7 issue, lets check other errors. In order to request a query to a MYSQL database, we need to create a connection:
$con = mysqli_connect("ip_address","user","password","database_name");
Once we have that connection, let us check if we can actually connect to the database:
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
Appreciate that mysqli_error() function uses the connection. Now the query string:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
You are sending a query to look for a username called "$login_session" and it would most likely not find any match. To add strings from variables will be as follow:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '" . $login_session . "'";
Now, for the error in line 7
result3 = mysql_query($con, $query3) OR die($mysql_error($con));
As you can see, both mysql function use the connection to check for errors. Try it and let me know if everything works fine.
Edit:
Terribly sorry my friend, I just forgot to put a little letter "i" on the line, also, I would like to show you my way to deal with the query result. First, the line as it should be:
$result3 = mysqli_query($con, $query3);
Notice the i after mysql. Now let us check whether we got some rows or not:
if (!$result3) {
die('Could not retrieve data: ' . mysqli_error($con));
} else {
while ($row = mysqli_fetch_array($result3)) {
//Show your results
}
}

PHP/MySQL where clause returning an empty value

I have a small problem using the Where clause for PHP/MySQL in the code shown below:
<?php
$con=mysqli_connect("host","username","password","database");
//Note that I have replaced my parametres just for this question
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Request Session ID
$id = $_SESSION['uid'];
echo "Session ID = ' . $id;
echo "<br>";
//Request Username
echo "Username = " . mysqli_query($con,"SELECT username FROM 'users' WHERE id = 4");
?>
The output of this is (after logging in on my separate login page):
Session ID = 4
Username =
So it is evident that there is an issue with the where clause.
There is no issue with the connection parametres as far as I am aware.
When I run the MySQL command in PHPmyadmin I get the expected result of 'Admin'.
My inputs are correctly named.
I have no idea what is causing this and I can't find any similar problems on the forum. Any help would be appreciated. Thanks.
UPDATE
I have adapted the below answers to make this code:
<?php
// Only run this script if the sendRequest is from my flash application
if ($_POST['sendRequest'] == "parse") {
//conection:
$con=mysqli_connect("mysqlXX.000webhost.com","a4935911_***","***","a4935911_***");
$id = $_SESSION['uid'];
$getuname = mysqli_fetch_assoc(mysqli_query($con, "SELECT username FROM users WHERE id = $id"));
$uname = $getuname ['username'];
// Print 1 var to flash
print "var1=The username of this user is $uname.";
}
?>
Which is triggered by my flash application. This works fine if I do not use session ID variable and just use e.g. 4 as my id value but I need to use the session ID for this. Any ideas what is up with this?
You shouldn't surround table names with ordinary single quotes ('); use backticks instead (or, if you don't use reserved words, none). So:
SELECT username FROM `users` WHERE id = 4
or
SELECT username FROM users WHERE id = 4
Moreover, mysqli_query doesn't return the result in the field, but a mysqli_result object. You'll have to use a fetch command to get the result(s), e.g.
$result = mysqli_query($con,"SELECT username FROM 'users' WHERE id = 4");
$row = mysqli_fetch_assoc($result);
echo 'Username = ' . $row['username'];
You should use the following code:-
//conection:
$con=mysqli_connect("host","username","password","database");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$getuname = mysqli_fetch_assoc(mysqli_query($con, "SELECT username FROM users WHERE id = 4"));
$username = $getuname ['username'];
//Request Username
echo "Username = " .$username ;

trying to count entries in a database

I'm trying to count entries in a database based on 2 basic criteria. It is returning a blank result, even though there are results to be found. Anyone have any idea what I am doing wrong here? I have tried it so many different ways and they all return no result. (If I enter the query directly in phpmyadmin it returns a result.)
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
$numericalResult = mysql_query($sql, $con);
$row = mysql_fetch_object($numericalResult);
$totalOrders1 = $row->total_count;
echo "My orders:" . $totalOrders1;
As others stated, make sure you sanitize variables before they go into query.
$sql = "SELECT * FROM orderOption3Detail WHERE orderDate = '" . $orderDate . "' AND studentID = '" . $studentID . "'";
$sql_request_data = mysql_query($sql) or die(mysql_error());
$sql_request_data_count = mysql_num_rows($sql_request_data);
echo "Number of rows found: " . $sql_request_data_count;
That's all you need.
Edited: providing full code corrected:
$con=mysqli_connect($db_host,$db_user,$db_pass,$db_name); // Check connection
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //global option 1
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
//echo $sql;
$numericalResult = $con->query($sql);
$row = mysqli_fetch_object($numericalResult);
echo $row->total_count; //echo (int) $row->total_count;
Please test this and let me know. Good luck!
----- End Editing ----
Have you tested assigning values directly as a test in your SQL string, like:
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='05/23/2012' AND studentID='17'";
Also, did you check if the date's format is correct, reading that $orderdate variable and testing it in PHPMyAdmin?
Did you read the $sql with values inserted and test in PHPMyAdmin and worked?
Also, check the connection to assure there is no problem there.
One more thing, sorry. You seem to be using the wrong syntax in your mysql_query statement. That way works for mysqli_query, and the parameters would be inverted. Try only:
$numericalResult = mysql_query($sql);
Provided you made the connection and database selection previously, like in:
$connection=mysql_connect($db_host, $db_username, $db_password);
if (!$connection)
{
$result=FALSE;
die('Error connecting to database: ' . mysql_error());
}
// Selects database
mysql_select_db($db_database, $connection);
Best wishes,

no db connection but no error

here is my db connection code and query code:
// Connecting, selecting database
$link = mysql_connect('MySQLA22.webcontrolcenter.com', 'shudson', '*******')
or die('Could not connect: ' . mysql_error());
mysql_select_db('henrybuilt') or die('Could not select database');
$sql = "SELECT ID, vcImageName FROM corp_images WHERE idPage = 6";
$query = mysql_query($sql) or die ("Error");
There is no 'or die' error upon connecting, selecting, or querying
There is no error_log file
The sql query executes if I run it in my sql browser
What is going on???
$sql = "SELECT ID, vcImageName FROM corp_images WHERE idPage = 6"
Its missing ;
$sql = "SELECT ID, vcImageName FROM corp_images WHERE idPage = 6";
It appears correct...try adding this adapted code from the manual to further debug and see what you learn:
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sql;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($query)) {
echo $row['ID'];
echo $row['vcImageName'];
}

Categories