How to search between all tables? mysqli - php

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

Related

Error creating SQL statement

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.

view works fine, but return 0 rows when call in php

I created folowing view (select list of last active users):
SELECT U.login, U.name, U.surname
FROM sessions S LEFT JOIN user U
ON S.id_user = U.id_user
WHERE U.id_user != 0 AND UNIX_TIMESTAMP()-S.set_time < 300
ORDER BY S.set_time DESC
SELECT *FROM vonline; gives me(i call it in phpmyadmin):
login name surname
admin Chuck Norris
user2 John Cena
I am trying to get same output in php:
if ($stmt = $mysqli->prepare("SELECT * FROM vonline")) {
$stmt->execute();
$result = $stmt->get_result();
echo "Online users: $stmt->num_rows"; // This shows "0"
while ($row = $result->fetch_array(MYSQLI_NUM)) {
echo "Login: $row[1] Name: $row[1] Surname: $row[2]";
}
} else {
echo "Select Error";
}
Why get no results, num_rows returns 0.
The code above works perfectly for selecting data from other tables, but not for this one.
Firstly, you're passing your code inside a string literal, rather than an executable.
echo "Online users: $stmt->num_rows"; // This shows "0"
That should read as
echo "Online users: " . $stmt->num_rows;
and using concatenation.
Example from the manual:
if ($result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
http://php.net/manual/en/mysqli-result.num-rows.php
Change $stmt->num_rows to $result->num_rows which I feel you are using the wrong variable. You need to use the variable on the "result" and the get_result() function.
However, get_result() may not be available for you to use.
Consult this Q&A on Stack:
What's wrong with mysqli::get_result?
As well as the manual http://www.php.net/manual/en/mysqli-stmt.get-result.php
Also make sure you're using the same MySQL API to connect with as your query.
Check for errors also against your db and query:
http://php.net/manual/en/mysqli.error.php
Edit:
This does not help you if there are errors in your query:
else {
echo "Select Error";
}
Change $stmt->execute(); to read as
if(!$stmt->execute()){
trigger_error("there was an error....".$mysqli->error, E_USER_WARNING);
}
Or use
echo("Error description: " . mysqli_error($mysqli));
in your else.
Plus, make sure you did select the right "database".

Getting 0 result from MySQL database , while my query and database name every thing is right

I have prefixed the custom and deafaults tables of wordpress.
Also I have put data in tables but I'm getting result 0.
Connection to database is ok and working
$sql = "SELECT u_name, u_email FROM jobify_user";
$result = $conn->query($sql);
if ($result->num_rows> 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
return "id: " . $row["u_name"]. "name:".$row["u_email"]. " <br>";
}
}
else {
return "0 results";
}
$conn->close();
Considering so the prefix is "jobify" and you're using wordpress tables, and according to https://codex.wordpress.org/Database_Description#Table:_wp_users, the table_name must be jobify_users, and columns must be user_name and user_email.
So, your query must surely be :
$sql = "SELECT user_name, user_email FROM jobify_users";

MYSQL Query Error Every Time

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

PHP update table data based on other table

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.

Categories