Trying to get field data to fit into if inarray() check - php

Just wondering if anyone can help me with this problem...
I want to be able to check if a certain ID (user for example is logged on) The ID's of these users will be pulled from a table, and then fed into an array and then checked if it is in there.
However when I pull the data the if inarray() no longer works as it would if I just typed it in straight within the code instead of pulling it.
I want to pull approved ID's through so they can access a certain link essentially!
Any help would be appreciated! Thanks!
<?php
mssql_select_db("$ins", $con);
$result = mssql_query("SELECT ID FROM Event WHERE EventPublic LIKE 'Yes' AND EventDate >= GETDATE() -1 ORDER BY EventDate ASC ");
while($row = mssql_fetch_array($result))
{
$test = "". $row['ID'] .",";
}
$tests = explode(',', $test);
if (in_array("2, 48", $tests)) {
echo "WOO";
}
else
{
echo "BOO";
}
mssql_close($con);
?>

in array should be an actual array
in_array(array('2', '48'), $tests)
also, it would be better to put
$tests = array();
before the while loop, then change the code inside the loop to read
$tests[] = $row['ID'];
then you can do away with the '$tests = explode(...' line.

Your having the issue with your in_array test because you are comparing an array and with a string in the following line:
if (in_array("2, 48", $tests))
The above line checks if the string "2, 48" exist in the array. But the array will have 2 as one element and 48 as a separate element. To fix this you can search for each element individually with something like:
if(in_array('2',$tests) || in_array('48',$tests))

Related

How to find out automatically the numeric index of an specific MySQL column in PHP?

I´m new to PHP and SQL and it´s the first time I post here, hope I do it right =)
I need to find out the numeric index from an certain field in my database. Thing is I´m not done with the database structure yet, so for this specific field I´d like to have it automated so I won't have to change the code every time I add or remove columns.
I also need it to have BOTH index types so I can call the columns by name in part of the code and by index for automated parts of it.
I´ve managed to achieve the result I wanted trough an very ugly code, because all the array_search and array_keys I´ve tried didn´t work out for some reason.
Here is the snippet of my working but ugly code. Do you have an more elegant solution?
Thanks in advance for your answers, and for all I´ve learned so far from reading other peoples questions!
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes) or die(mysql_error());
$c = 0; // This block is to find out where the column "cont1" is and assign it to $cont1
$d=array_keys($student);
$cont1=0;
foreach ($student as $a=>$b){
if ($a==='cont1') {
$cont1=$d[$c-1];
}
$c++;
}
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$students[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$students[$i+2]."</li>";
echo "</ul></p>";
}
}
Finding the numeric index:
$student = mysqli_fetch_array($dadosRes,MYSQLI_ASSOC) or die(mysql_error());
$numericIndex = array_search("cont1",array_keys($student));
Giving MYSQLI_ASSOC will force the query to fetch only the associative keys; otherwise it will give you both numeric and associative array.
PHP function, array_search in this case, requires the third parameter set to TRUE:
<?php
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes, MYSQLI_BOTH) or die(mysql_error());
$student_keys = array_keys($student);
$cont1 = $student_keys[array_search("cont1", $student_keys, true) - 1];
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$student[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$student[$i+2]."</li>";
echo "</ul></p>";
}
}
?>
MYSQLI_BOTH is used in the mysqli_fetch_array function because first the array is searched for the column name, then later the array is looped over with numeric indexes. This results in the $student array having integer 0 as the first element and therefore causing array_search to choke. Adding true as the third parameter causes a === comparison unchoking the function. :) (Explanation: PHP array_search consistently returns first key of array )

Selecting different items in a fetch array

When using mysql_fetch_array, i pass the array data to a separate variable. My question is how do i access the different items held in that array by their position?
Preferably i want to call each item in turn have a calculation run on that item and if the result is the lowest number so far, pass that data to a variable.
Any help is appreciated, thanks.
<?php
$query = "SELECT postcode FROM freelance ORDER BY id";
$result = mysql_query($query);
while($postcode = mysql_fetch_array($result)) {
echo "<span>" . $postcode['postcode'] . "</span></br>";
}
?>
Instead of echo out all postcodes how would i define to only output the third item in the array
Solution 1:
You can display them with a foreach in the while:
foreach($postcode as $data) {
echo $data;
}
Solution 2:
You can call them by position (starts with 0):
$postcode[0]
$postcode[1]
$postcode[2]
...
Read more about array's : http://www.php.net/manual/de/language.types.array.php
When you call mysql_fetch_array, you are getting the results of the next row returned by your query. In this case, your query is returning a result set with one column, postcode, and many rows (presumably). Your while loop is just getting each row's postcode value and echoing it in a <span>.
EDIT: I have changed my code example in reponse to the OP's comment.
I am not really familiar with what it is you are trying to do, but hopefully my example makes some sense (you will have to fill in some blanks with your code). For one, I don't think you need to store the results from the database into one big array and then go through each record to determine the lowest distance. You are already looping through each record in your while loop, make use of it!
<?php
$inputcoords = //I assume that you already have the coordinates for the input postal code somewhere
$query = "SELECT postcode FROM freelance ORDER BY id";
$result = mysql_query($query);
while($postcode = mysql_fetch_array($result)) {
$curpostcode = $postcode['postcode'];
$curcoords = //calculation/function/something that calculates the current coordinates from $curpostcode
$distance = //Haversine formula using $curcoords and $inputcoords (you'll have to figure this part out)
if (!isset($lowest) || $distance < $lowest) {
$lowest = $distance;
//optional: if you want to keep track of which postal code gave the shortest distance...
$lowestpostcode = $curpostcode;
}
}
//go on to use the calculated distances for something...
?>
Also, as a side note, mysql_* functions are deprecated. If at all possible, you should switch to mysqli or PDO.

while loop into in array

What am I trying to do is collect data from a while loop, store it into a variable. Then later in my code I see if some variable is equal to one of the values in the array and then to echo out the two other column values I got from the while loop but equal to the row that the value came from. I have tried a bunch different things and am so close but cant get it exactly.
while($row = mysql_fetch_assoc($query)){
$team[] .= "{$row['team']}";
$winslosses .= "({$row['wins']} - {$row['losses']})";
}
this returns something like
$team = (bears, badgers, wildcats)
$winslosses = ((42-24), (55-23), (32-21))
Then later in my code I want to see if its equal to a value in the array then echo $winslosses.
if(in_array(bears, $team) ) {echo '$winslosses';}
This shows all the wins and losses from each team. I want it only show me the record of the bears.
Any help would be great.
You can use array_search() to get the index of an item in an array. You can then use that index when querying $winlosses:
$team = array(bears, badgers, wildcats);
$winslosses = array("(42-24)", "(55-23)", "(32-21)");
$key=array_search(bears, $team);
echo $winslosses[$key]
results in:
(42-24)
Your best bet would be to store them in an associative array.
while($row = mysql_fetch_assoc($query)){
$winslosses[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Hope this helps
Your main problem is that you currently have $winslosses as a string, not an array, so you can't easily pull out the win/loss record for just one team.
There are several ways you could do this. The one that seems easiest to me would be to put it together as one array up front.
Something like...
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Then later on...
if(array_key_exists("bears",$teams)) {
echo $teams["bears"];
}
Or even better, store the wins/losses as a sub-array, so you have structured data that you can format however you want later on.
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = array("wins" => $row['wins'], "losses" => $row['losses']);
}
echo $teams['bears']['wins']; // for example
Use associative array:
while($row = mysql_fetch_assoc($query)){
$team[] = {$row['team']};
$winslosses[$row['team']] = "{$row['wins']} - {$row['losses']}";
}
Then retrieve it like this:
if(in_array(bears, $team) ) {
echo $winslosses['bears'];
}
As a matter of fact, if you do not need the names of the teams in a separate array, you can just use one associative array and then retrieve it.
if (array_key_exists('bears', $winslosses)) {
echo $winslosses['bears'];
}

Saving 2 variable's values for later use

I tried to make the title of this most the most descriptive as possible, as I don't know how to do this... I know the best way will be value storage in some form of array.
My question is this, I have this query where I need to pic the tag name and the correspondent id for a later comparison and use ($tag_nome is collected by $_GET):
$resultado2 = mysql_query("SELECT tag.tag_nome, rel_frasetag.id_tag
FROM tag, rel_frasetag
WHERE rel_frasetag.id_tag = tag.id_tag AND
rel_frasetag.id_frase='$id_frase'") or die(mysql_error());
while($res2 = mysql_fetch_array($resultado2))
{
$tag_nome2 = utf8_encode($res2['tag_nome']);
$id_tag = $res2['id_tag'];
}
I already tried some things like array_push() but couldn't get it to work.
At the end of this snippet I'm comparing $tag_nome2 against $tag_nome to see if they match. If so, it will echo one link with the corresponding $tag_nome2 and $id_tag, and if not will echo pretty much the same thing, with a different class on the link.
My best guess as far as what you want to do is the following:
if( $tag_nome2 == $id_tag )
{
// do something
}
else
{
// no match
}
Perhaps though, you're saying your variable names are being overwritten? You're inside of a while loop, so the values they'll ultimately receive will be that of $res2[] at the end of the last iteration of your loop.
And if you're saying you want to save your rows for later, you can do:
$holder = array();
$res = mysql_query("");
while( $row = mysql_fetch_assoc($res) )
{
$holder[] = $row;
}
print_r($holder);

create array from mysql query php

I have a little problem that I don't understand. I have a db that has an owner and type (and more off course). I want to get a list of all the type values that has owner equal to the current user, but I get only two result
$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ORDER BY id DESC ";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
prints out:
Array ( [0] => 18 [type] => 18 )
and
$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ";
prints out:
Array ( [0] => 16 [type] => 16 )
And the result should be something like 19, 19, 18, 17, 16 in an array. Thats all the types that has me as set as owner.
I have got this working now:
for ($x = 0; $x < mysql_num_rows($result); $x++){
$row = mysql_fetch_assoc($result);
echo $row['type'];
}
Here I print out all the values correctly, but I need to create an array with all the values. I though I could use array_push, but there most be a better way of doing it. I thought I would get all the type values with a simple mysql query.
Very often this is done in a while loop:
$types = array();
while(($row = mysql_fetch_assoc($result))) {
$types[] = $row['type'];
}
Have a look at the examples in the documentation.
The mysql_fetch_* methods will always get the next element of the result set:
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
That is why the while loops works. If there aren't any rows anymore $row will be false and the while loop exists.
It only seems that mysql_fetch_array gets more than one row, because by default it gets the result as normal and as associative value:
By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
Your example shows it best, you get the same value 18 and you can access it via $v[0] or $v['type'].
THE CORRECT WAY ************************ THE CORRECT WAY
while($rows[] = mysqli_fetch_assoc($result));
array_pop($rows); // pop the last row off, which is an empty row
You do need to iterate through...
$typeArray = array();
$query = "select * from whatever";
$result = mysql_query($query);
if ($result) {
while ($record = mysql_fetch_array($results)) $typeArray[] = $record['type'];
}
while($row = mysql_fetch_assoc($result)) {
echo $row['type'];
}
You could also make life easier using a wrapper, e.g. with ADODb:
$myarray=$db->GetCol("SELECT type FROM cars ".
"WHERE owner=? and selling=0",
array($_SESSION['username']));
A good wrapper will do all your escaping for you too, making things easier to read.
$type_array = array();
while($row = mysql_fetch_assoc($result)) {
$type_array[] = $row['type'];
}
You may want to go look at the SQL Injection article on Wikipedia. Look under the "Hexadecimal Conversion" part to find a small function to do your SQL commands and return an array with the information in it.
https://en.wikipedia.org/wiki/SQL_injection
I wrote the dosql() function because I got tired of having my SQL commands executing all over the place, forgetting to check for errors, and being able to log all of my commands to a log file for later viewing if need be. The routine is free for whoever wants to use it for whatever purpose. I actually have expanded on the function a bit because I wanted it to do more but this basic function is a good starting point for getting the output back from an SQL call.

Categories