PHP select multiple tables from MYSQL - php

I'm beginner at PHP & MYSQL I don't know where is the error at this code first MySQL database contains 6 tables I've no equation to JOIN them together and I want to show the last added value of each table
<?php
$servername = "localhost";
$username = "project";
$password = "pro2018";
$dbname = "project";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql_temp = "select * from temp order by id desc limit 1 ";
$sql_hum = "select * from hum order by id desc limit 1 ";
$sql_soil1 = "select * from soil1 order by id desc limit 1 ";
$sql_soil2 = "select * from soil2 order by id desc limit 1 ";
$sql_soil3 = "select * from soil3 order by id desc limit 1 ";
$sql_soil4 = "select * from soil4 order by id desc limit 1 ";
$result_temp = $conn->query($sql_temp);
$result_hum = $conn->query($sql_hum);
$result_soil1 = $conn->query($sql_soil1);
$result_soil2 = $conn->query($sql_soil2);
$result_soil3 = $conn->query($sql_soil3);
$result_soil4 = $conn->query($sql_soil4);
//if ($result_->num_rows > 0) {
// output data of each row
$row_temp = $result_temp->fetch_assoc()) ;
$row_hum = $result_hum->fetch_assoc()) ;
$row_soil1 = $result_soil1->fetch_assoc()) ;
$row_soil2 = $result_soil1->fetch_assoc()) ;
$row_soil3 = $result_soil1->fetch_assoc()) ;
$row_soil4 = $result_soil1->fetch_assoc()) ;
$x = $row_temp["value"];
$y = $row_hum["value"];
$a = $row_soil1["value"];
$b = $row_soil2["value"];
$c = $row_soil3["value"];
$d = $row_soil4["value"];
echo " $x" . " Degree";
echo " $y" . " %";
echo " $a" . " %";
echo " $b" . " %";
echo " $c" . " %";
echo " $d" . " %";
header("Refresh:5");
?>

Welcome to Stack overflow!
First off, consider using PDO objects in PHP. PDO are the latest way to talk to databases in PHP. It is a more generalized platform that can talk to many more diffrent types of database. PHP manual here. Outline of differences between MySqli and PDO here(external).
Second, without joining, you can't return the data from more than one table at a time in one SQL SELECT statement. You will need to do multiple requests, as you have in your code example.
You could make the process more streamlined, though, by having an array of the tables you want to get data from:
$tableArray = array(
'tableOne'=>"<name of table one>",
'tableTwo'=>"<name of table two>",
...
);
$resultArray = array();
//get results from server
foreach($tableArray as $curKey=>$curTable){
//ONLY SAFE IF $tableArray IS NEVER CHANGED
$curStmt = "SELECT * FROM ".$curTable." order by id desc limit 1;";
$resultArray[$curKey] = //set this to the result from the sql statement
}
//print them out
foreach($resultArray as $curKey=>$curValue){
echo $curKey. " " . $curValue;
}
This method lets you setup the tables you want to get the info from in one place and do everything you need for you.
Make sure that your list of table names can never be edited though (just never assign it beyond the initial definition). Unfortunately, you cannot use a table name as a parameter for prepared statements, so you must build the sql statements yourself (as shown in my example), opening up the possibility for SQL injection. If you never assign the values of your table array outside of the initial definition, you should be fine though.
( I know the link explaining that tables as parameters doesn't work is specifically for java, but the issue there is SQL querying, not Java based)

Related

Mysql Join two tables to check if a user has made a pick

Hi I am attempting to join two MySQL tables. The tables are as follows:
Table 1
Name: mlb_game_feed
Fields: game_feed_game_id, date, home_team, away_team
Table 2
Name: user_picks
Fields: pick_id, game_feed_game_id_fk, user_id_fk
Here is the sql I've attempted to use to join the two tables:
$sql = "
SELECT game_feed_game_id
, home_team
, away_team
, COUNT(1) as cnt
FROM game_feed_mlb
JOIN user_picks
ON user_picks.game_feed_game_id_fk = game_feed_mlb.game_feed_game_id
Where game_feed_mlb.date = '" . $_SESSION['date']."'
AND user_picks.user_id_fk = 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$count = $row["cnt"];
$game_id = $row["game_feed_game_id"];
$home_team = $row['home_team'];
$away_team = $row['away_team'];
echo $game_id;
}
}
My intention is to check if the user has picked a winner (either home_team or away_team) from the mlb_game_feed table and if they have, I will change a link from make_pick to change_pick (with an if($count) statement) on the screen.
However, currently I'm not even getting any data back which means my sql is likely incorrect. Any help would be great! Thanks.
Consider the following suggestions:
Use a LEFT JOIN to return ALL records and a conditional aggregate to count matches in cnt field. Later you can use this cnt to run your update hyperlink in PHP. See if block in fetch loop.
As mentioned, your SQL string that concatenates on line breaks does not leave room before the clauses of SQL: FROM, JOIN, ON, and WHERE.
Use a GROUP BY clause for your aggregate query. Non-aggregated columns must appear in this clause else it is a violation of ANSI SQL. Unfortunately, MySQL allows the ONLY_FULL_GROUP_BY mode off whereas every other RDBMS will correctly throw an error.
Use table aliases for more readable code instead of repeating long name tables.
Pass in $SESSION date as a parameter to prepared statement. See ? placeholder in string.
PHP
$sql = "SELECT g.game_feed_game_id, g.home_team, g.away_team, " .
" SUM(CASE WHEN g.game_feed_game_id IS NOT NULL " .
" THEN 1 ELSE 0 END) as cnt " .
"FROM game_feed_mlb g " .
"LEFT JOIN user_picks u " .
" ON u.game_feed_game_id_fk = g.game_feed_game_id " .
"WHERE g.`date` = ? AND u.user_id_fk = 1 " .
"GROUP BY g.game_feed_game_id, g.home_team, g.away_team;"
// CONFIGURE PREPARED STATEMENT AND BIND PARAMETER
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_SESSION['date']);
// EXECUTE STATEMENT AND RETURN RESULTS
$stmt->execute();
$result = $stmt->get_result();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$count = $row["cnt"];
$game_id = $row["game_feed_game_id"];
$home_team = $row['home_team'];
$away_team = $row['away_team'];
echo $game_id;
if($row['cnt'] > 1) {
// change links accordingly...
}
}
}

MySQL query with output to PHP page

I am trying to make simple page which will return values from MySQL table, but the problem is that if I want to use condotions in query then it doesn't work.
My PHP page:
<?php
$servername = "10.10.10.10";
$username = "username";
$password = "password";
$dbname = "GENERIC_TABLES";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT WO_NUM+1 from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> WO Number ". $row["WO_NUM"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
So, WO_NUM column has numbers like 1, 2, 3 etc.
I want to get the last one + 1
So if I do like:
$sql = "SELECT WO_NUM from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1";
Then it works fine, but if I want to make it WO_NUM + 1 then it returns nothing.
Why it happens like that and is there any way to get what I want using MySQL?
I don't want to get WO_NUM and then using PHP make it + 1, since I also need INSERT to the table values and I would like to understand why it doesn't work.
As you realized, WO_NUM+1 changes the column name in the resulting array, so use an alias WO_NUM+1 as NEW_NUM. However I would not bother with the sorting and limit. Consider MAX():
SELECT max(WO_NUM)+1 as NEW_NUM from GENERIC_TABLES.WO_NUMBERS
As it has been pointed by AbraCadaver, I missed that if I am using WO_NUM + 1 then column name changing so that is why i didn't get any output, so using alias solved problem.

Save Postgres query in PHP variable

I have the following Postgres query:
$sql_afect = "SELECT SUM(r.num_tiempo_afectado) FROM ctl_reportes r
WHERE 1 = 1 AND r.num_tiempo_afectado <> '00:00:00' " . (!empty($idu_clase) ?
"AND r.idu_clase = $idu_clase" : "") . " " . (!empty($idu_prioridad) ?
"AND r.idu_prioridad = $idu_prioridad" : "");
I'm working on a PHP program, and this query sums a bunch of some specific hours, which are in this format on a table (ctl_reportes): '00:00:00'.
How could I save this query's result into a PHP variable in order to echo the result on the screen?
See the code below to execute query in PHP using PDO
<?php
$user = 'root';
$pass = 'toor';
$dbh = new PDO('mysql:host=localhost;dbname=db_scrapper', $user, $pass);
$query = "SELECT SUM(r.num_tiempo_afectado) FROM ctl_reportes r
WHERE 1 = 1 AND r.num_tiempo_afectado <> '00:00:00' " . (!empty($idu_clase) ?
"AND r.idu_clase = $idu_clase" : "") . " " . (!empty($idu_prioridad) ?
"AND r.idu_prioridad = $idu_prioridad" : "");
$sth = $dbh->prepare($query);
$sth->execute();
/* Exercise PDOStatement::fetch styles */
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $sth->fetch(PDO::FETCH_ASSOC);
var_dump($result);
Here after query is executed, the result is stored in $result. I assume you have some
basic knowledge to use PHP. Please refer to PHP PDO to have more insights into it.
Please let us know if this works for you or not. And I'll update my answer accordingly.

Using PHP to pull data from MySQL table column randomly

I am using the following (assume I already plan to change these to mysqli at a later date and am aware of the insecurity of the queries used), to pull text strings from rows in one column in a MySQL table and the output in a browser would, ideally, be a randomly selected string from this column:
mysql_connect($host,$username,$password);
mysql_select_db($database) or die(mysql_error ());
$query="SELECT * FROM `tablename` ORDER BY RAND() LIMIT 0,1;";
$result=mysql_query($query);
$rows = array();
while($row = mysql_fetch_array($rs)) {
$rows[] = $row;
}
mysql_close();
$max = count($rows) - 1;
Using the following echo line to achieve the last bit in the browser:
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4]$
?>
I receive the error "PHP Notice: Undefined offset: 0 in script.php on line 19" in reference to this echo line (which, admittedly, was pieced together from other threads and tutorials, so I do not follow completely), however, I've since resolved all other errors logged and observed, so if possible, how can I amend this so the output is just a single row (the text within it) from the column?
Faster and better than using RAND()
$conn = mysqli_connect($host,$username,$password, $database);
if($conn->connect_errno > 0) {
die('Unable to connect to database [' . $conn->connect_error . ']');
}
$total_rows = 20; //Generate Random number. You could get $total_rows with a first query counting all rows.
$selected_row = mt_rand(0, $total_rows);
//$selected_row -= 1; //just in case you randomized 1 - $total_rows and still need first row.
//Use the result in your limit.
$query="SELECT * FROM `tablename` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
echo $row["columnname"];
}
Edit it from mysql to mysqli (on the fly). You would not want to use RAND() if your table is very large. Believe me!
In your SELECT-statement, you are telling the database to order the strings randomly. So just get the first one and echo it:
$row = mysql_fetch_array($rs)
echo $row['name_of_field_you_want_to_echo'];
You never define the variable $rs. Other than that...
If you are selecting the first items from a SQL query, you don't need to specify both the limit and top.
$result = mysql_query("SELECT * FROM `tablename` ORDER BY RAND() LIMIT 1");
Since that will ever return one row, you can use mysql_fetch_row
$row = mysql_fetch_row($result);
and then you can get the field from that row with
echo $row["column_name"];

php random mysql data

I have a MySQL database with 6 columns in a table. There will eventually be about 100 rows, for now I have 3.
Column titles: FirstName, SecondName, Sentence1, Sentence2, Sentence3, Sentence4
All tables are set to VARCHAR
I want to use php on a web page to call random data from each row, eg mix and match row1 FirstName with row3 SecondName and row2 Sentence1 etc.
I read it is quicker to randomise using php but I really can't grasp how to do this despite searching.
I can connect to my MySQL database and get results returned using this code:
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "yyy") or die (mysql_error ());
// Select database
mysql_select_db("zzz") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['FirstName'] . "<br />";
}
// Close the database connection
mysql_close();
?>
but this just returns one column of data. I need the random code to be returned in the webpage using something like:
echo $firstname . $lastname . $sentence1 . $sentence2 . $sentence3 . $sentence4;
Note, this will be repeated for another 3 or 4 rows afterwards too
echo $firstname_2 . $lastname_2 . $sentence1_2 . $sentence2_2 . $sentence3_2 . $sentence4_2;
I'm not too hot on arrays but if someone can get me started it would be great, thanks.
All those telling you to use rand in the SQL query have not read the question. To those people: the asker wants a random combination of data from the rows, not a random row.
Something like this. It will take all the results from the database and echo a totally random combination. I couldn't avoid using arrays as they are super useful.
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "yyy") or die (mysql_error ());
// Select database
mysql_select_db("zzz") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Array to hold all data
$rows = array();
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// add row to array.
$rows[] = $row;
}
// Close the database connection
mysql_close();
// Max rand number
$max = count($rows) - 1;
// print out random combination of data.
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4] . " " . $rows[rand(0, $max)][5];
?>
Store all the values which you want to show in random in a variable, use rand() http://php.net/manual/en/function.rand.php and shuffle() http://php.net/manual/en/function.shuffle.php to make the random data and display them
there are several methods to get random data from db in php
SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;
another method: -
$range_result = mysql_query( " SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM `table` ");
$range_row = mysql_fetch_object( $range_result );
$random = mt_rand( $range_row->min_id , $range_row->max_id );
$result = mysql_query( " SELECT * FROM `table` WHERE `id` >= $random LIMIT 0,1 ");
one more method:-
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `table` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `table` LIMIT $offset, 1 " );
SELECT * FROM `Users` ORDER BY RAND() LIMIT 0,1;
Use ORDER BY RAND() for random records selection.
Split it into two tables,
one for the user
Users:
id | firstname | lastname
Sentences:
id | userId | sentence
Join both at the "id / userId" and do a ORDER BY RAND() probably followed by a LIMIT 20
Trying to implement this but taking an entry from every column (14 at present) instead of a small random number. Would love to have Matthew McGovern's opinion since his code suited me except that it only called a few entries...
Here: Random Sentence Using PHP & MySQL

Categories