I made the following code to try and grab the number of entries in 3 tables in a database. The queries work when I use them in phpMyAdmin but when I run this code I get:
Error creating SQL statement
which is generated by the if(!$stmt) statement and I have no idea why it's not working. Thanks in advance :)
<?php
include 'connection.php';
$countArtists = $countAlbums = $countTracks = 0;
/* Create queries to get counts from each table */
$sql = "SELECT COUNT(*) FROM artist;";
$sql .= "SELECT COUNT(*) FROM cd;";
$sql .= "SELECT COUNT(*) FROM tracks;";
$stmt = $conn->prepare($sql);
if(!$stmt)
{
echo "Error creating SQL statement";
return 1;
}
$stmt->execute();
$stmt->bind_result($countArtists, $countAlbums, $countTracks);
echo "<li>Number of Artists: $countArtists</li><br>\n" .
"<li>Number of Albums: $countAlbums</li><br>\n" .
"<li>Number of Tracks: $countTracks</li><br>\n";
?>
I think you want a single query like this:
$sql = "SELECT (SELECT COUNT(*) FROM artist) as countArtists, ".
"(SELECT COUNT(*) FROM cd) as countAlbums, ".
"(SELECT COUNT(*) FROM tracks) as countTracks";
This is one query with three columns, as opposed to three separate queries.
Related
If I put the name of one table it's work, but if I type * it does not find anything.
I trying to search at all the tables that exist in the specific db,
Basically it is for a search box on the site
i need help please
<?php
$link = mysqli_connect("localhost", "***", "***", "***");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if(isset($_REQUEST["term"])){
$sql = "SELECT * FROM * WHERE food LIKE ?";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "s", $param_term);
$param_term = $_REQUEST["term"] . '%';
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p><a style='color:red' href='http://hidden.com'>" . $row['date'] . "</a></p>";
}
} else{
echo "<p>No matches found</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
mysqli_stmt_close($stmt);
}
mysqli_close($link);
?>
You must assigne table name esplicitally the use of * ( select all) is not allowed for table name .. you can use just one name or you can use JOIN for join several tables but in your case, assuming each table have a column named food , you could if you need a query that involve mores table you could use union
SELECT *
FROM table1
WHERE food LIKE ?
UNION
SELECT *
FROM table2
WHERE food LIKE ?
UNION
SELECT *
FROM table3
WHERE food LIKE ?
......
UNION
SELECT *
FROM tablen
WHERE food LIKE ?
";
You can use UNION for distinct result or UNION ALL for get all the result
SQL doesn't support wildcarding on tables.
You can run "SHOW TABLES" first which will give you a list of tables in one query result. Then you can iterate through those and run your query on each table individually.
If you need to do it in one shot, you'll need to create a stored procedure which does the same thing, but would all be run on the server-side
I am attempting to use a drop-down list to pull Pokémon info back from a database that I've uploaded, and I keep getting the following error:
No Pokemon was requestedDatabase access failed: You have an error in
your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'WHERE pokemon_name =
SELECT * FROM pokemon_info' at line 1
I have a database currently with the headings:
id | pokemon_name | height | weight | gif
I literally can't figure out why... My processing code is as follows;
// CODE TO QUERY DATABASE TO GO HERE
// Capture form data, if anything was submitted
if (isset($_POST['pokemon_submit'])) {
$pokemon_submit = clean_string($db_server, $_POST['submit']);
// create the SQL query
$query = "SELECT * FROM pokemon_info where pokemon_info=$pokemon_submit";
// query the database
mysqli_select_db($db_server, $db_database);
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
// if there are any rows, print out the contents
if ($row = mysqli_fetch_array($result)) {
$output .= "Pokemon: " . $row['pokemon_name'] . ", Gif: " .
$row['gif'] . "<br />";
}
else {
$output = 'Well, you must have invented a new Pokémon, cause it is not on this website!';
}
mysqli_free_result($result);
}
else {
$output = 'No Pokemon was requested';
}
// CODE TO QUERY END
}
// Close connection!
// YOUR CODE HERE BIT end
echo $output;
$output = '';
mysqli_select_db($db_server, $db_database);
$query = "WHERE pokemon_name = $pokemon_submit SELECT * FROM pokemon_info";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$output .= "Pokemon: " . $row['pokemon_name'] . ", Gif: " .
$row['gif'] . "<br />";
}
mysqli_free_result($result);
echo $output;
I have now amended thanks to your help, and it's saying that no Pokémon was requested.
The basic idea of this is to have a main page with a drop-down list of pokemon. When a user selects from the list, the information stored in my database about that specific pokemon is displayed.
The drop-down list is linked directly to the pokemon_name column in my database. I don't understand why it's coming back as though nothing is selected?
Thank you all SO much for your help, I'm learning much more here than trawling through forums.
There are more than one issue(s)
$query = "SELECT * FROM pokemon_info where pokemon_name=$pokemon_submit";
if pokemon_submit is a number - it is ok. If it is a string then you need
$query = "SELECT * FROM pokemon_info where pokemon_name='$pokemon_submit'";
notice the single quotes.
$query = "WHERE pokemon_name = $pokemon_submit SELECT * FROM pokemon_info";
$result = mysqli_query($db_server, $query);
I have no clue what you're trying here? I know of no SQL statements begin with "WHERE"
WHERE pokemon_name = $pokemon_submit SELECT * FROM pokemon_info
is not a valid query.
If you want to select the pokemon $pokemon_submit from pokemon_info, what you do is this;
SELECT * FROM `pokemon_info` WHERE `pokemon_name` = '$pokemon_submit'
The WHERE comes after SELECT. More on the doc page.
I'd also look into verifying data before putting it into the query, OOP approach to MySQLi and general SQL syntax.
I urge you to look at the other comments. Your querying looks fundamentally unsafe. However, I believe that your actual issue is here:
if (isset($_POST['pokemon_submit'])) {
$pokemon_submit = clean_string($db_server, $_POST['submit']);
First, you look for $_POST['pokemon_submit'], but when you clean the string, you use $_POST['submit'].
Insted of WHERE pokemon_name = $pokemon_submit SELECT * FROM pokemon_info try altering your query to something like ...
WHERE pokemon_name in $pokemon_submit SELECT pokemon_name FROM pokemon_info
The second part of your query is returning multiple results. ie..... Select * from pokemon_info.
So we refine that to get only the pokemon names back ie..
select pokemon_name from pokemon_info
And the first part of the query will only want names where the name matches any of the results from the second part of the query
Your full query should look something like
select * from pokemon_info WHERE pokemon_name in $pokemon_submit SELECT pokemon_name FROM pokemon_info
or in short
select * from pokemon_info where pokemon_name = $pokemon_submit
I have a simple function that returns a count from a database table, based on some criteria.
function MyCount($strTable, $strCriteria) {
$strSQL = "SELECT COUNT(*) FROM " . $strTable . " ";
if (trim($strCriteria) != "") $strSQL .= "WHERE " . $strCriteria;
$results = mysql_query($strSQL, $objConn);
$row = mysql_fetch_array($results);
return $row[0];
}
Its very useful for quickly getting a value in 1 line of code, e.g:
$Users = MyCount("Users", "Deleted = 0");
However, I'm now trying to move to PDO and am having trouble passing in the were as parametrized values. I'm trying to do something like the below (which doesn't work):
$objQuery=$objConn->prepare("SELECT count(*) as TheCount FROM :table_name WHERE :criteria");
$objQuery->bindParam(':table_name', $strTable);
$objQuery->bindParam(':criteria', $strCriteria);
I guess the obvious would be:
$objQuery=$objConn->prepare("SELECT count(*) as TheCount FROM :table_name WHERE ".$strCriteria");
$objQuery->bindParam(':table_name', $strTable);
But, this seems to go against the spirit of parametrized values... does anyone have any other suggestions?
Thanks
This line is the issue:
$objQuery->bindParam(':table_name', $strTable);
You can only bind values ( field= :value) in PDO you cannot bind table names or column names or custom dynamic where clause.
So you just build the query manually:
SELECT count(*) as TheCount FROM `$strTable` WHERE $strCriteria
function my_count($strTable, $strCriteria, $objConn)
{
$sql ="SELECT count(*) as TheCount FROM $strTable WHERE $strCriteria";
$objQuery=$objConn->query($sql);
$row =$objQuery->fetch();
return $row['TheCount'];
}
$Users = my_count("Users", "Deleted = 0", $objConn);
select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product;
select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price;
This query works in mysql console
but
$query = "
select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product;
select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price;
";
$result = mysql_query($query);
this code raise error in php
so, I tried this
$query="
select * from ct_product, (select #min_price:=min(prd_sale_price),#max_price:=max (prd_sale_price) from ct_product) as b
where prd_sale_price=#min_price or prd_sale_price=#max_price
";
$result = mysql_query($query);
that works
...
$query = "
select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product;
select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price;
";
$result = mysql_query($query);
What's the way that this code would work well without modification as my second way?
Use two calls to mysql_query:
$query1 = "select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product";
$query2 = "select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price";
mysql_query($query1);
mysql_query($query2);
Variables are associated with a database connection, so they'll persist between the calls.
in PHP mysql_query() can handle only one query at a time
You can't make this method handle 2 query at the same time
what I can suggest is using mysql_query() for every query
I am trying to create a cron job that will select the sum of points from a transaction table.
Based on the Sum of the points and the employee id I must update the total point table.
I want to make sure that I am using the best method and that this will work.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT ID, SUM(POINTS) as Points, FROM Transactions WHERE Status = 1 Group By ID";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
mysql_query("UPDATE Totals SET Points=" + $row["Points"] + "WHERE ID=" + $row["id"]);
}
mysql_free_result($result);
?>
You can still join tables (and subqueries) on UPDATE statements. Try this one,
UPDATE Totals a
INNER JOIN
(
SELECT ID, SUM(POINTS) as Points,
FROM Transactions
WHERE Status = 1
Group By ID
) b
ON a.ID = b.ID
SET a.Points = b.Points
Hope this helps.
example of using PDO Extension (Code Snippet).
<?php
$query = "UPDATE Totals a
INNER JOIN
(
SELECT ID, SUM(POINTS) as Points,
FROM Transactions
WHERE Status = ?
Group By ID
) b
ON a.ID = b.ID
SET a.Points = b.Points";
$iStatus = 1;
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $iStatus);
$stmt->execute();
?>
PDO Manual
PDO PreparedStatement
Why can't you just test the script out out before you run it via a cron job? I can't spot anything that's wrong with the syntax; but then again, I only gave it a quick glance and I don't know what your table structure is like.
If you're looking for the BEST way to do things, then you should looking into using mysqli or PDO instead of the mysql functions. That way, you can make use of prepared statements, which won't be as taxing on your DBMS if you're planning on running multiple queries inside a loop. Prepared statements don't require you to make separate round trips to the server, whereas the old mysql functions do.