MYSQL order limit with PHP variable - php

This is my code below
$query = mysql_query("SELECT * FROM table ORDER BY id LIMIT 10");
while($f = mysql_fetch_array($query)){
$match = 0; //In reality it's an array search function which returns 1 on match
if($match == 1) {
echo"Show content!";
}
}
Im trying to make an list with 10 rows, and i have a function which uses "name" from table to run an search query with an array generated by twitter API. In example if i get 3 matching records, i still want to show a list with 10 rows but hide the matching elements from there.
At the moment the script hides the matching elements and shows 7 rows instead of 10.
That is what i need help with, cheers :)

Process the data you are getting from the twitter api, collect the data you need in an array and query the database afterwards.
Something like that:
<?php
$collectArray = array();
foreach ($twitterData as $index => $data) {
if ($someCriteria === TRUE) {
$collectArray[] = $data;
}
}
$implodedCollectArray = "'" . implode("', '", $collectArray) . "'";
$sql = "SELECT * FROM `table_name` WHERE `some_column` IN (" . $implodedCollectArray . ")";
$query = mysql_query($sql) or die(mysql_error());
while($f = mysql_fetch_array($query)){
echo $f['column'];
}
?>

reinitilize match variable as the code:
$query = mysql_query("SELECT * FROM table ORDER BY id LIMIT 10");
while($f = mysql_fetch_array($query)){
if($f['name']!='variable_name_twiter'){
$match = 1; //In reality it's an array search function which returns 1 on match
}
if($match == 1) {
echo"Show content!";
}
$match = 0;
}

Related

My for loop only allows one post to be displayed, over and over again

/* To sort the id and limit the post by 40 */
$sql = "SELECT * FROM requests";
$result = $conn->query($sql);
$sqlall= "SELECT * FROM requests ";
$resultall = $conn->query($sqlall);
$i = 0;
if ($result->num_rows > 0) {
// Output data of each row
$idarray= array();
while($row = $result->fetch_assoc()) {
echo "<br>";
// Create an array to store the
// id of the blogs
array_push($idarray,$row['id']);
}
}
else {
echo "0 results";
}
?>
<?php
for($x = 1; $x < 40; $x++) {
// This is the loop to display all the stored blog posts
if(isset($x)) {
$query = mysqli_query(
$conn,"SELECT * FROM `requests`");
$res = mysqli_fetch_array($query);
$email1 = $res['email1'];
$msg1= $res['msg1'];
$subject1 = $res['subject1'];
$name1 = $res['name1'];
$id = $res['id'];
the output is 40 cards reading data from the first row in my database. can anyone help?
I'm using xampp.
This code is to show the loop, but if anyone wants the full code is here
You are storing all the IDs in the array $idarray, but then you don't really use them properly. You loop over them, but you just run SELECT * FROM requests` 40 more times, and always extract the same first row. You never use the ID to change the query.
But it really makes no sense to run lots of separate queries anyway. If you just want the first 40 rows then use MySQL's LIMIT keyword. It usually works best when combined with ORDER BY as well. Something like this:
$sql = "SELECT * FROM requests ORDER BY id LIMIT 40";
$result = $conn->query($sql);
while ($res = $result->fetch_assoc()) {
$email1 = $res['email1'];
$msg1 = $res['msg1'];
$subject1 = $res['subject1'];
$name1 = $res['name1'];
$id = $res['id'];
//example output, just for demo:
echo $email1." ".$msg1." ".$subject1." ".$name1." ".$id;
}
Documentation: https://dev.mysql.com/doc/refman/8.0/en/limit-optimization.html

PHP mysql query issue when filtering from array and variables

On my webpage (html, php), I'm trying to get it such that users may select multiple checkboxes, each checkbox effectively filters what results the users see. Info is pulled from the database (MySQL) based on the values in different columns. As shown below, one column is Joint_1, another column is Position.
Effective code that WORKS for filtering (very static, not practical to use obviously) is this:
$sql = "SELECT * FROM `Table_Name` WHERE (Joint_1=\'region1\' OR
Joint_1=\'region2\' OR
Joint_1=\'region3\' OR
Joint_1=\'region4\') AND
(Position=\'position1\' OR
Position=\'position2\' OR
Position=\'position3\')";
$result = $conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["Common_Name1"] . "<br>";
}
} else {
echo "0 results";
}
Below code is attempts at above code, but using arrays, which does NOT work.
$regions =
array('region1', 'region2', 'region3', 'region4');
$position = array('position1', 'position2', 'position3');
$sql = "SELECT * FROM `Table_Name` WHERE (Joint_1=\'. $regions[0] .\' OR
Joint_1=\'. $regions[1] .\' OR
Joint_1=\'. $regions[2] .\' OR
Joint_1=\'. $regions[3] .\') AND
(Position=\'. $position[0] .\' OR
Position=\'. $position[0] .\' OR
Position=\'. $position[0] .\')";
Above code provides results of '0 results.'
I've attempted to perform this numerous times, with additional NON-FUNCTIONAL CODE also below (below attempting to filter based on only 1 column as I have obviously not mastered the code to approach filtering based on 2 columns).
$sqlregion = array();
foreach ($_POST['region'] as $reg) {
$sqlreg[] = "'" . mysql_real_escape_string($reg) . "'";
}
$sql = "SELECT * FROM 'Exercises' WHERE Joint_1 IN (" . implode(",",
$sqlreg) . ");";
$result=$conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["Common_Name1"] . "<br>";
}
}
Any help is appreciated! Thanks.
You can construct this query from arrays, you can use the IN clause in mysql to specify multiple OR values
$regions = array('region1', 'region2', 'region3', 'region4');
$position = array('position1', 'position2', 'position3');
$regions = implode(",", $regions); // Converts array to string with comma as a separator
$position = implode(",", $position);
$sql = "SELECT * FROM `Table_Name` WHERE Joint_1 IN ($regions) AND Position IN ($position)";
echo $sql;
This gives you a query like this
SELECT * FROM Table_Name WHERE Joint_1 IN (region1,region2,region3,region4) AND Position IN (position1,position2,position3)
add in your own LIMIT GROUP BY or ORDER BY parameters to suit your needs

Get the column names and field values for one record using MySqli

I am trying to get the column names and field values from a table for ONE record. If a column name was 'sellers' and the field value was 'Bob', the desired output would be: seller Bob
The output will actually be used for a script like this:
$fields['sellers']->setValue($sellers);
Where 'sellers' is the column name and $sellers is the field value.
There are dozens of columns in the table.
The script below only outputs the column names - not the field values.
Any help is appreciated.
$sql = "SELECT * FROM tbl_pdfform WHERE trans_id = '$trans_id' ";
$sql_result = mysqli_query($db, $sql);
for($i = 0; $i < mysqli_num_fields($sql_result); $i++) {
$field_info = mysqli_fetch_field($sql_result);
$col = "{$field_info->name}";
echo $col . ' ';
while ($row = mysqli_fetch_array($sql_result)) {
$data = $row[$col];
echo $data."<br>";
}
}
Not sure if I exactly understand what you're trying to do but would using mysqli_fetch_assoc() and a foreach loop give your desired result?
$sql = "SELECT * FROM tbl_pdfform WHERE trans_id = '$trans_id' ";
$sql_result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($sql_result);
foreach($row as $column => $value) {
echo $column . " " . $value;
}
You should just call mysqli_fetch_array() once, not in a loop for each column. Because every time you call it, it moves to the next row of results, it doesn't re-fetch the old row. Since you only have one row of results, the repeated calls just return false.
$row = mysqli_fetch_array($sql_result);
for($i = 0; $i < mysqli_num_fields($sql_result); $i++) {
$field_info = mysqli_fetch_field($sql_result);
$col = "{$field_info->name}";
echo $col . ' ' . $row[$col];
}
But there isn't really any need to use mysqli_fetch_field() to get the field names. Since $row is an associative array, the field names are just the keys of the array. However, it would be better to use mysqli_fetch_assoc(), because mysqli_fetch_array() returns an array that contains both named and numbered elements; mysqli_fetch_assoc() just returns the named elements. So the answer by WheatBeak is how most would do what you want.
I think that there's a problem with the interpolation.
$sql = "SELECT * FROM tbl_pdfform WHERE trans_id = '$trans_id' ";
Using variables between apostrophes sends the string "$trans_id" in the SQL query instead of the value which $trans_id contains. Try this:
$sql = "SELECT * FROM tbl_pdfform WHERE trans_id = '" . $trans_id . "' ";

can't find multiple values in SQL

I have a DB full of players and I am trying to create a page to register them into a specific tournament. The tournament director will search for players by username (which is only "firstname.lastname").
The problem I'm experiencing is that when I run loop to echo each $players[$x] it only gives the ID for the first matching DB record, and repeats the number once for each match. Rather than returning ID 7, 11, 26 it will return 7, 7, 7. Please can someone explain why?
I have written the following code in a .php file:
session_start();
if (isset($_POST['newsearch']) === true && empty($_POST['newsearch'] === false)){
require 'dbconnect.php';
$term = $_POST['newsearch'];
$terms = "%" . $term . "%";
$query = ("SELECT PlayerID FROM players WHERE Username LIKE '$terms'");
$run_query = mysqli_query($dbcon, $query);
$search = mysqli_fetch_assoc($run_query);
$players = array ();
do{
//Get data from players table
$PlayerID = $search['PlayerID'];
array_push ($players, $PlayerID);
}
while ($dbsearch = mysqli_fetch_assoc($run_query));}
You have more that one fetch for the same query, replace the code after $run_query = mysqli_query($dbcon, $query); with this code:
$players = array ();
while ($dbsearch = mysqli_fetch_assoc($run_query))
{
array_push($players, $dbsearch['PlayerID']);;
}
Your while loop is wrong
$query = ("SELECT PlayerID FROM players WHERE Username LIKE '$terms'");
$run_query = mysqli_query($dbcon, $query);
$search = mysqli_fetch_assoc($run_query);
$players = array ();
do{
//Get data from players table
$PlayerID = $search['PlayerID'];
array_push ($players, $PlayerID);
}
while ($search = mysqli_fetch_assoc($run_query));
}
Put $search instead of $dbsearch
$search = mysqli_fetch_assoc($run_query))
Note : your query is vulnerable to SQLI

Why isn't this script working? (odd/even)

I've been writing a script to display the names of users based on whether they are assigned an even or odd comment id. It calls up data from 2 different tables in the same database. Here is the table information:
Table 'comments' has the columns commentid, tutorialid, name, date: Table 'winners' has the columns pool, pool2, pool3, pool4, pool5, pool6, pool7. Table 'comments' has multiple rows that are updated through user input. Table 'winners' has only 1 row with numbers that are randomly generated daily.
The first part of the script that displays "Result 1" and "Result 2" is working properly. The part that isn't working is the part that calls up the usernames. I only want to display the usernames that corralate with the result that is displayed IE if Result 1 is chosen then I only want the usernames with even 'commentid's displayed.
<?php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
if ($row['pool'] % 2) {
echo "<h4>Result 1</h4>";
$names = get_names(1);
foreach($names as $name) {
echo $name . "<br/>";
}
} else {
echo "<h4>Result 2</h4>";
$names = get_names(0);
foreach($names as $name) {
echo $name . "<br/>";
}
}
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments where mod('commentid',2) = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
}
?>
Can anyone figure out why this isn't working?
The SELECT statement with the mod is not referencing the field. Should be backticks instead of single quotes. Single quotes indicate a string constant, which would result in a constant result set (mod('commentid',2) appears to have a result of 0). It should be something like this:
$query = "SELECT * FROM comments where mod(`commentid`,2) = $pool_result";
Adding quotes around commentid treats it as a string, and you can't mod a string by an integer. Try the following instead:
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
This was taken from the following Stack question: select row if the "value" % 2 = 1. MOD()

Categories