I have a database which simply records words in a table in a single column (with RID beside). All I want to do is display the words in order with a space in between (which I have a working code for below)
<?php
$mysql_host = "mysql1.000webhost.com";
$mysql_database = "db name";
$mysql_user = "user";
$mysql_password = "pass";
// Create connection
$conn = new mysqli( "mysql1.000webhost.com","databaseuser","password","databasename");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'SELECT Words FROM Poetry ';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["Words"]. " ";
}
} else {
echo "0 results";
}
?>
HOWEVER. I want to only display a set amount (say 50) of the MOST RECENT db entries (i.e) the 50 with the highest RID. Can somebody quickly tell me what code I need (in php) which will display the 50 most recent on a web page?
Thanks!
Don't do it with PHP, just add it to your query.
$sql = 'SELECT Words FROM Poetry order by RID desc limit 50';
This query will order the result set by RID descending, most recent first I'm assuming, and limit the result set to 50 records.
You can use
SELECT Words FROM Poetry order by RID desc limit 0,50
0 is the offset and 50 is limit.u can dynamically change those value if needed.
For the better security purpose You can use mysqli prepared statements.
You can see dynamically-bind_param-array-mysqli for Dynamically Bind Params
Try saving it in a variable and echoing it after your while statement.
Something like this
$all_words = '';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$all_words = "$all_words, $row['Words']";
}
echo"$all_words";
} else {
echo "0 results";
}
Related
I'm trying to loop through each row of a table in a database, then once I'm on a particular row get the value of a certain column. Is this possible? I've done a couple Google searches but nothing really concrete. I try using the mysqli_fetch_array() function but when I do I get the results of a column. I want to target each row. The code I have so far gets me the "nid" column. That's not what I want. I want to iterate through each row.
<?php
$serverName = "localhost";
$username = "user1";
$password = "sp#99#1";
$databaseName = "developer_site";
// Connection
$connection = new mysqli($serverName, $username, $password, $databaseName);
// Check Connection
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
} // line ends if statement
$queryNodeRevision = "SELECT nid FROM node_revision";
// line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
echo "NID: ";
echo $row['nid'];
echo "<br/>";
}
?>
You can select rows by a certain condition with an SQL query alone and also select all columns.
SELECT * FROM node_revision where condition;
condition could be anything. For example another_row = 'something'.
But if, for some reason, you need to process the nid inside your php script to know if that row is the "particular" one you're searching, then you just select all the columns, or the ones you need.
$queryNodeRevision = "SELECT nid, col1, col2 FROM node_revision";
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
if (condiiton) {
echo "Particular: ".$row['nid']
." ".$row['col1']
." ".$row['col2'];
}
}
condition could be something like $row['nid'] == 123 for example.
Hope it helps.
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.
I have a big 2D array (576,000 X 4), and huge database (millions records and 10 columns, its size is in Gigabytes). The array, of course, is much smaller than the number of records in the database.
I need some effective way to compare the 2D array to the database, and delete the equal lines from the 2D array only.
Does anyone have an idea how could i apply it efficiently? The speed is very important to me.
I tried to apply it like that:
$query = mysqli_query($config, "SELECT * FROM sec ") or die(mysql_error());
while ($row = mysqli_fetch_array($query) ) {
if ( isset($arr[$row['CHROM']][$row['POS']]) ) {
// delete line from the 2D array
}
}
But, i don't know how efficient it is, because i tried it just on small database, and it makes me load all the records of the database to the PHP page, and it creates a memory problem.
Another way that i check is this:
foreach ($arr as $chr=>$v) {
foreach ($v as $pos=>$val) {
$query = mysqli_query($config, "SELECT * FROM sec WHERE CHROM='$chr' && POS='$pos' ") or die(mysql_error());
if (mysqli_num_rows($query) > 0) {
// delete line from the 2D array
}
}
}
But, its not a good solution, because it took too much time.
edit:
my sec table looks like that:
the call to a item from the 2D array looks like that $arr[some_CHAROM][some_POS]
if the some_CHAROM equal to some CHAROM in the database AND some_POS equal to the POS in the same line, we have a match.
i build the 2D array from a file that the user upload to the website. and im not load it to the mySql.
The algorithm:
convert the file uploaded by the user into a CSV file (if not already in this format); this is a simple task that can be done in several lines of PHP code; see function fputcsv();
create a buffer table: tbl1;
use LOAD DATA LOCAL INFILE to load the content of the (local) CSV file into the buffer table tbl1;
use:
DELETE tbl1
FROM tbl1
INNER JOIN tbl2 on tbl1.id = tbl2.id
to delete from table tbl1 the rows that have matches in table tbl2. I assumed the match field is named id on both tables; change it to match your design;
fetch the data from table tbl1, format it as you wish, send it to the browser;
cleanup: DROP TABLE tbl1;
Because the script processes a file uploaded by an user, in order to avoid any concurrency issue you need to generate for the buffer table an unique name for each user. You can use a prefix and append the userId to it to avoid two users using the same table on the same time.
Try following code
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "drupal7";
mysql_connect($servername, $username, $password );
mysql_select_db($dbname);
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$database1=array();
while ($row = mysql_fetch_row($result)) {
$result1 = mysql_query("SELECT * FROM ".$row[0]);
if(mysql_num_rows($result1)){
$num_rows = mysql_num_rows($result1);
// echo "Table: {$row[0]} ==>".$num_rows."<br>";
$database1[$row[0]]=$num_rows;
}
// }
}
echo '<pre>';
print_r($database1);
mysql_free_result($result);
// mysql_close();
$dbname='drupal71';
mysql_select_db($dbname);
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$database2=array();
while ($row = mysql_fetch_row($result)) {
$result1 = mysql_query("SELECT * FROM ".$row[0]);
if(mysql_num_rows($result1)){
$num_rows = mysql_num_rows($result1);
// echo "Table: {$row[0]} ==>".$num_rows."<br>";
$database2[$row[0]]=$num_rows;
}
// }
}
print_r($database2);
$test = array_diff($database1, $database2);
print_r($test);die;
From your code snippet
foreach ($arr as $chr=>$v) {
foreach ($v as $pos=>$val) {
$query = mysqli_query($config, "SELECT * FROM sec WHERE CHROM='$chr' && POS='$pos' ") or die(mysql_error());
if (mysqli_num_rows($query) > 0) {
// delete line from the 2D array
}
}
}
I assume, that you want to delete based on $chr and $pos.
So, you could do the following: Assemble a single query to rule them all* :)
$ors = array();
foreach ($arr as $chr=>$v) {
foreach ($v as $pos=>$val) {
$ors[] = "CHROM='$chr' AND POS='$pos'";
}
}
$deleteConditions = "(" . implode(") OR (", $ors) . ")":
$query = mysqli_query($config, "DELETE FROM sec WHERE " . $deleteConditions);
Untested, but this should give you a single query, like
DELETE FROM
sec
WHERE
(CHROM='1' AND POS='2') OR
(CHROM='3' AND POS='4') OR
(CHROM='5' AND POS='6') OR
...
depending on what $chr and $pos are.
*As Ollie Jones noted in the comments: Take care of the overall query length. If required, create a second, third, ... query until you processed all items in appropriate batches.
I need to have two datasets of 10,000 randomly generated values between 1 and 10,000 and find only the values that are common between the datasets. I then need to sort them from least to greatest. I cannot use array_intersect() or array_unique().
It appears I was able to accomplish this using a while loop to generate the random integers for both MySQL tables and compare and sort them using a MySQL Query. I'm not completely sure if my results are accurate though and I am looking for a more efficient way to complete this task. Can someone please tell me if I am successfully completing my task and what would be alternative ways to solve this. I need to know if my Select Statement is producing the correct results and how I could improve it.
<?php
// CONNECT TO THE DATABASE
$DB_NAME = 'e3';
$DB_HOST = 'localhost';
$DB_USER = 'e3';
$DB_PASS = 'exercise3password';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$x = 0;
while($x <= 10000){
$randa = rand(1,10000);
$randb = rand(1,10000);
$query = "INSERT into a (num) VALUES ($randa)";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$query = "INSERT into b (num) VALUES ($randb)";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$x++;
}
$query = "SELECT * FROM a INNER JOIN b on a.num=b.num WHERE a.num=b.num ORDER BY a.num";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
// GOING THROUGH THE DATA
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo stripslashes($row['num']);
echo "<br>";
}
}
else {
echo 'NO RESULTS';
}
// CLOSE CONNECTION
mysqli_close($mysqli);
?>
Your WHERE clause merely reaffirms a condition previously specified in your ON clause. As such it's redundant. Also, to improve efficiency, remove '*' and instead name each of the columns you actually want returned. Apart from that, your query is fine.
I have the code below which is supposed to check the database for entries with a certain username which is working but when I try to add some code to check if the rows returned is greater than 10 and then run some code to limit the number of rows to 10 and then if not run another piece of code which will display all the rows.
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$checkres = mysql_query("SELECT COUNT link, notes, titles, color FROM links WHERE username='" . $username . "';");
if ($checkres>10)
{
$resultsmall = mysql_query("SELECT link, notes, titles, color FROM links WHERE username='" . $username . "' LIMIT 10;");
while ($rowsmall = mysql_fetch_array($resultsmall)) { //loop
extract($rowsmall);
$htmlsmall .= "
//code goes here to format results
";
echo $htmlsmall; //display results...
}
}
else {
$result = mysql_query("SELECT link, notes, titles, color FROM links WHERE username='" . $username . "';");
while ($row = mysql_fetch_array($result)) { //loop
extract($row);
$html .= "
//code goes here to format results
";
echo $html; //display results...
}
}
mysql_close($con); //close db..
But it just displays two times the number of rows in the database instead of either limiting it or displaying them all. How would I fix this? The //code goes here for formatting isn't important it just formats the code so that it looks nice and displays it in a box...
Thanks!
EDIT:
I now have this code but it now doesn't display anything at all? Can someone help:
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT SQL_CALC_FOUND_ROWS link, notes, titles, color FROM links WHERE username='" . $username . "' LIMIT 10";
$result = mysql_query($sql) or die("MySQL error: " . mysql_error());
$subsql = "SELECT found_rows() AS foundrows;";
$subresult = mysql_query($subsql) or die("MySQL error: " . mysql_error());
$found_rows = $subresult['foundrows'];
if($found_rows > 10)
{
while($row = mysql_fetch_array($result))
{
extract ($row);
$html .= "
//getting values from columns and then formatting them goes here
";
echo "Only 10 is allowed.";
}
}
else
{
while($row = mysql_fetch_array($result))
{
extract($row);
$html .= "
//getting values from columns and then formatting them goes here
";
}
}
mysql_close($con); //close db..
Thanks!
EDIT 2 (12 April 14:03 2011 GMT):
I now have this code which has been kindly helped by Col. Shrapnel but it doesn't display anything for me and I don't know why, please could some help.
Code:
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT link, notes, titles, color FROM links WHERE username='$username' LIMIT 10";
$res = mysql_query($sql);
if (mysql_num_rows() == 10) {
while ($row = mysql_fetch_array($res)) {
extract($row);
$htmlsmall .= "
=
";
$htmlfree .= "Only 10 is allowed.";
echo $htmlsmall;
echo $htmlfree;
}
}
else {
while ($row = mysql_fetch_array($res)) {
extract($rowsmall);
$htmlsmall .= "
";
echo $htmlsmall;
}
}
Now if I view the page source I can see these 2 errors:
<b>Warning</b>: Wrong parameter count for mysql_num_rows() in <b>//url was here</b> on line <b>109</b><br />
<b>Warning</b>: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>//url to file goes here</b> on line <b>125</b><br />
Line 109 is this: if (mysql_num_rows() == 10) {
Line 125 is this: while ($row = mysql_fetch_array($res)) {
(Those lines are in the code above)
Please could someone help me with this?
Thanks!
mysql_query() returns either a result statement handle, or boolean FALSE if the query failed. Your outer query is invalid:
SELECT COUNT ...
does not work, so the query fails, returns false, which jumps to the lower "unlimited" query.
However, you're going about the process of limiting things in a roundabout fashion that forces the query to run at least twice.
What you want is
$sql = "SELECT SQL_CALC_FOUND_ROWS link, notes, etc.... LIMIT 10";
$result = mysql_query($sql) or die("MySQL error: " . mysql_error());
$subsql = "SELECT found_rows() AS foundrows;";
$subresult = mysql_query($subsql) or die("MySQL error: " . mysql_error());
$found_rows = $subresult['foundrows'];
if ($found_rows > 10) {
... there's more than 10 rows available, though we're fetching only 10 because of the LIMIT
} else {
... 10 rows or less
}
The SQL_CALC_FOUND_ROWS is a MySQL extension that forces MySQL to calculate how many rows would have been fetched, if the LIMIT clause had not been present. You can get the results of this calculation with the found_rows() query function.
This way, you only run the main query once, do the very very quick found_rows() query, and off you go.
Given that you don't seem to be formatting your output any differently between the "more than 10" and "10 or less" version, except for the "only 10 allowed" line, how about this:
$sql = "...";
$result = mysql_query($sql) or die(mysql_error());
$rowcount = 0;
while ($row = mysql_fetch_assoc($result)) {
$rowcount++;
... output a row ...
if ($rowcount > 10) {
echo "Only 10 allowed";
break;
}
}
There's no need for duplicated code, excess logic, etc... when something simple will do.
I try to add some code to check if the rows returned is greater than 10 and then run some code to limit the number of rows to 10
It makes no sense.
Just run your query with LIMIT 10 and you will get your data.
mysql_select_db("blahblah", $con); //connect to database..
$username = basename(dirname(__FILE__));
$username = mysql_real_escape_string($username);
$sql = "SELECT * FROM links WHERE username='$username' LIMIT 10";
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
while ($row = mysql_fetch_array($res)) {
extract($rowsmall);
$htmlsmall .= ""; //code goes here to format results
}
echo $htmlsmall;
That's all.
If you still want to echo "Only 10 is allowed." (dunno why though) you can add these 3 lines below
if (mysql_num_rows($res) == 10) {
echo "Only 10 is allowed.";
}
However I see not much point in it.
Also note that your program design is probably wrong, as you're apparently copying this file for the every user in your system
To get number of rows returned in result you must use mysql_num_rows.
if (mysql_num_rows($checkres)>10)