can't find multiple values in SQL - php

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

Related

Placing single column database values into an array then calling them in another query

I'm having trouble with pulling database information from 'rownum' column and putting it into an array and then using that array information for my next query that randomly selects one line of the array and then displays it.
<?php
// Connect to database
include 'DB.php';
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($databaseName, $con);
// Select Rownum to get numbers and only where there is no value in seen.
$firstquery = "SELECT rownum FROM num_image WHERE seen=''";
// If there are results store them here
$result = mysqli_query($firstquery) or die ("no query");
// Put the results taken from the table into array so it displays as: array(56, 44, 78, ...) etc...
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
// Select the data I require
$query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE rownum='$row' LIMIT 1;");
$test = mysqli_query("UPDATE num_image SET Seen='yes' WHERE rownum='$row';");
// Fetch Results of Query, Ignore test.
$arrayss = mysqli_fetch_row($query);
// Echo Results as a Json
echo json_encode($arrayss);
?>
I'm not sure what I have done wrong? Does the array have to be echoed and then my $query line calls that instead?
Updated code - Solved my problem
Thanks for tips guys, it helped me wrap my head around it and came up with a working solution.
<?php
// Connect to database
include 'DB.php';
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($databaseName, $con);
// Select Rownum to get numbers and only where there is no value in seen.
$firstquery = "SELECT rownum FROM num_image WHERE seen=''";
// If there are results store them here
$result = mysqli_query($firstquery) or die ("no query");
// Put the results taken from the table into array so it displays as: array(56, 44, 78, ...) etc...
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
for ($i = 0; $i < count($result_array); $i++) {
$all_rownums[] = implode(',', $result_array[$i]);
}
//pick a random point in the array
$random = mt_rand(0,count($all_rownums)-1);
//store the random question
$question = $all_rownums[$random];
// Select the data I require
$query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE rownum='$question' LIMIT 1;");
$test = mysqli_query("UPDATE num_image SET Seen='yes' WHERE rownum='$question';");
// Fetch Results of Query, Ignore test.
$arrayss = mysqli_fetch_row($query);
// Echo Results as a Json
echo json_encode($arrayss);
?>
This part is what helped me solve it:
for ($i = 0; $i < count($result_array); $i++) {
$all_rownums[] = implode(',', $result_array[$i]);
}
Happy Dance

Output is array, how to fix this?

Right now I am selecting some data from Mysql which I want to echo out, but I don't know how..
Code
<?php
// Database connection
require_once($_SERVER["DOCUMENT_ROOT"] . "/includes/config.php");
require_once($_SERVER["DOCUMENT_ROOT"] . "/includes/opendb.php");
// News 1
$searchroutenews1 = "SELECT newsid FROM NewsHomepage WHERE id = '1'";
$handlenews1 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenews1);
$news1 = mysqli_fetch_row($handlenews1);
$searchroutenewsimg1 = "SELECT newsimg FROM NewsHomepage WHERE id = '1'";
$handlenewsimg1 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenewsimg1);
$NewsImg1 = mysqli_fetch_row($handlenewsimg1);
// News 2
$searchroutenews2 = "SELECT newsid FROM NewsHomepage WHERE id = '2'";
$handlenews2 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenews2);
$news2 = mysqli_fetch_row($handlenews2);
$searchroutenewsimg2 = "SELECT newsimg FROM NewsHomepage WHERE id = '2'";
$handlenewsimg2 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenewsimg2);
$NewsImg2 = mysqli_fetch_row($handlenewsimg2);
// News 3
$searchroutenews3 = "SELECT newsid FROM NewsHomepage WHERE id = '3'";
$handlenews3 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenews3);
$news3 = mysqli_fetch_row($handlenews3);
$searchroutenewsimg3 = "SELECT newsimg FROM NewsHomepage WHERE id = '3'";
$handlenewsimg3 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenewsimg3);
$NewsImg3 = mysqli_fetch_row($handlenewsimg3);
?>
After this I require_once this in an other file, and then I echo the variables $news1, $news2, $news3, $NewsImg1, $NewsImg2 and $NewsImg3. But if I echo this variables out now it says: array.
You can fetch all this information via a single query, instead of the 6 you currently are running. Then it's a matter of putting mysqli_fetch_*() as the argument of a while, as you'll then fetch all the rows, until that function returns null - at which point you've fetched all the rows returned by the query.
$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT newsid, newsimg FROM NewsHomepage WHERE id IN (1, 2, 3)");
while ($row = mysqli_fetch_assoc($result)) {
echo $row['newsid']." ".$row['newsimg'];
}
Change however you need it to be displayed inside the while loop, and use the two variables as they are inside.
Alternatively, you can use WHERE id BETWEEN 1 AND 3 instead, but using IN (1, 2, 3) can more easily be changed to the exact ids you need.
http://php.net/mysqli-result.fetch-assoc
First you should read http://php.net/manual/en/mysqli-result.fetch-row.php
you can find there mysqli_result::fetch_row -- mysqli_fetch_row — Get a result row as an enumerated array mysqli_fetch_row always return array so now you can't echo array thats why it gives you array.
You can try foreach loop or for loop or while loop to display your data. there are also various methods to get array value.
Below is an example you can use.
while ($news1 = mysqli_fetch_row($handlenews1)) {
echo $news1[0];
}

Need Some Help Regarding Fetching Data from Mysql using explode function

In the below script I want to fetch data from mysql using a explode function and also a variable within an explode function.
Here's how I want to get
<?php
include ('config.php');
$track = "1,2,3";
$i = 1
$trackcount = explode(",",$track);
$sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['track_name']}";
}
mysql_free_result($retval);
?>
This is the code
$sql = "SELECT * FROM tracks WHERE id='$trackcount[$i]'";
I want sql to fetch data from tracks table where id = $trackcount[$i]
Whatever the value of $trackcount[$i] mysql should fetch but it shows a blank screen.
If I put this
$sql = "SELECT * FROM tracks WHERE id='$trackcount[1]'";
It works perfectly
save your $trackcount[$i] in one variable and then pass it in the query as given below
<?php
include ('config.php');
$track = "1,2,3";
$i = 1;
$trackcount = explode(",",$track);
$id=$trackcount[$i];
$sql = "SELECT * FROM tracks WHERE id='$id'";
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['track_name']}";
}
mysql_free_result($retval);
?>
and one more thing check your previous code with echo of your query and see what is passing ok.
echo $sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";//like this
problem is with your query
$sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";//change
to
$sql = "SELECT * FROM tracks WHERE id='$trackcount[$i]'";
Generally you would want to use the IN operator with this type of query, so for you this would be:-
$sql="SELECT * FROM `tracks` WHERE `id` in (".$track.");";
or, if the $ids are in an array,
$sql="SELECT * FROM `tracks` WHERE `id` in (".implode( ',', $array ) .");";

MYSQL order limit with PHP variable

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;
}

Trouble when passing a php variable as an argument in mysql query

I'm trying to use a php variable as a search term when querying a mysql database, first I get the variables from the HTML form:
<?php
//Create variables
$vals = array($_POST["id_number"], $_POST["id_name"], $_POST["id_submitname"]);
$keys = array('idno_1', 'name_2', 'subname_3');
//combine keys to arrays
$var = array_combine($keys, $vals);
//santise variables
$variables = filter_var_array($var, FILTER_SANITIZE_STRING);
$idno = $variables['idno_1'];
$name = $variables['name_2'];
$subname = $variables['subname_3'];
After connecting to the database I run the query:
//Select entry from table and display
if (!$idno == '')
{
$sql = "SELECT * FROM `healthsafety` WHERE ID = '$idno'";
$result = mysqli_query($connection, $sql);
}
elseif (!$name == '')
{
$result = mysqli_query($connection, "SELECT * FROM `healthsafety` WHERE LOWER (nameinvolved) = LOWER ('$name')");
}
else
{
$result = mysqli_query($connection, "SELECT * FROM `healthsafety` WHERE LOWER (submitbyname) = LOWER ('$subname')");
}
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
It is not returning anything from the db, when I select * FROM without trying to use the variable as a search it displays all entries ok, am I making an error when passing the variable to the query? I've tried different combinations of quotes, back ticks and using other variables for the query. Any help would be greatly appreciated!
LOWER is a function and the arguments needs to be wrapped in parentheses.
Your query should look like:
$result = mysqli_query($connection, "SELECT * FROM `healthsafety`
WHERE LOWER(nameinvolved) = LOWER('$name')");
For easier debugging, I'd first print out the query:
$query = "SELECT * FROM `healthsafety`
WHERE LOWER(nameinvolved) = LOWER('$name')";
echo $result;
... and then run it manually using the MySQL Interactive shell or using web interfaces like phpMyAdmin. That could help you isolate the issue further and then figure out what's wrong.
First you needed to be sure that all data are correct. then Try this:
if (isset($idno) && !$idno == '')
{
$sql = "SELECT * FROM `healthsafety` WHERE ID = $idno";
$result = mysqli_query($connection, $sql);
}
else if (isset($name) && !$name == '')
{
$result = mysqli_query($connection, "SELECT * FROM `healthsafety` WHERE LOWER (nameinvolved) = LOWER ('$name')");
}
else
{
$result = mysqli_query($connection, "SELECT * FROM `healthsafety` WHERE LOWER (submitbyname) = LOWER ('$subname')");
}
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

Categories