Problems with MAX( ) MYSQL call - php

I'm having trouble using the MAX aggregate function in my PHO code. What I'm trying to do is to select the highest user_id form my database. However, I get an error that says " Warning: mysql_result() [function.mysql-result]: image_id not found in MySQL result index 3 " If anyone could tell me what I'm doing wrong with my code it would be greatly appreciated!
$highest = "Select MAX(image_id) FROM image_table ";
$result2 = mysql_query ($highest);
if (!$result2) die ("Database acces failed: " . mysql_error ());
$rows2 = mysql_num_rows($result2);
for ($j=0; $j<$rows2; $j++)
{
echo 'highest image id: ' . mysql_result($result2, $j,'image_id') . '<br/>';
}
Also, is there a way to set a variable directly equal to the highest id. Say for example i wanted the variable $maxID to be equal to the current maximum id, which is 93...

You have two choices:
Use an alias - SELECT MAX(image_id) AS image_id FROM image_table ...
Use an offset - mysql_result($result2, $j, 0)
Also, I would suggest switching over to PDO. Here's an example of that:
$db = new PDO( ... );
$res = $db->query('SELECT MAX(image_id) FROM image_table');
if (false === ($maxId = current($res->fetchAll(PDO::FETCH_COLUMN, 0)))) {
// $maxId is definitely a number
}

Related

PHP select multiple tables from MYSQL

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)

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,

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

SQL Multiple Update Statements

I need to update 40 rows in a database, starting at the point where the userID is a match. I do not want to have to determine the row number because eventually this database will be huge.
What I would like to do is simply say:
"Update these the next 40 rows with my array where userID = myUserID"
Here is what I have:
<?php
// connect to the database and select the correct database
$con2 = mysql_connect("localhost","Database","Password");
if (!$con2)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ifaves_code", $con2);
$i = 0;
while ($i < 40) {
//cycle through the array
$cycleThrough2 = $updatedUserNames[$i];
//$query = "UPDATE tblUserLinks SET `URLName` = '$cycleThrough2' WHERE userID = '" . $mainUID . "' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
++$i;
}
mysql_close();
?>
The variable $mainUID is being set correctly, the problem I'm having is it appears there are no updates taking place in the database.
How can I alter my existing code to receive my desired behaviour?
I don't suppose it's because you have your query building statement commented out...
//$query = "UPDATE tblUserLinks SET `URLName` = '$cycleThrough2' WHERE userID = '" . $mainUID . "' LIMIT 1";
If this is just the result of debugging and it wasn't working before that, you must call mysql_error() right after mysql_query() to see why it is failing.
$result = mysql_query($query);
if (!$result) echo mysql_error();
Also, you are using LIMIT 1 at the end, but the userID never changes in the WHERE clause. Therefore, you are updating the same row over and over 40 times on each loop. What you need is a way in your WHERE clause to identify rows which have already been modified, and exclude them. Otherwise, the same row (first match) will always be caught by the LIMIT 1 and updated.

Categories