Using in_array to compare MySQL data - php

I have a table set up in MySQL with two columns:
ID (auto_increment)
recentlyplayed (VARCHAR, set up like "1 44" or "2 140", etc)
I'm trying to get the mysql data into an array and compare it to something defined outside MySQL. But it doesn't seem to work for some reason. Here is my code:
$whichPlaylist is a 1 character INT, and $num is a 3 character INT.
//Note: These values are actually received through file_get_contents('textfile.txt');
$whichPlaylist = "1";
$num = "44";
//Combine playlist number and video number
$joint = $whichPlaylist. "" .$num;
//Insert joint var into Mysql database
mysql_query("INSERT INTO recentlyplayed (numplayed) VALUES('$joint') ");
$query = "SELECT * FROM recentlyplayed";
$result = mysql_query($query) or die ("no query");
while($row = mysql_fetch_array($result))
{
$stored[] = $row['1'];
}
if (in_array($joint, $stored['1'])){
$reroll = 1;
}
echo $reroll;
Even if the same value of $joint is in the MySQL table, $reroll doesn't echo 1. Could this because of extra spacing when inserting the $joint variable? I'm actually getting the $whichPlaylist and $num from a text file that has a new line after the number. Any help is appreciated. :)

Move the While End braces after if statement, and see if it works.

Try this code in your script:
$stored = array();
while($row = mysql_fetch_array($result)) {
$stored[] = $row[1];
}
if (in_array($joint, $stored)){
$reroll = 1;
}
The array is $stored (not $stored['1']).

Related

Check if given value exists in array or mysql table

I would like to check if a given value exists in a mysql table. If yes; I would like to get the value of another column of that row.
Now I have:
$teinsertengetal=$_GET['getal'];
// start
$i = 0;
$ikhadingezetArray = array();
$result = $conn->query("SELECT getal, hoevaakingezet FROM ingezettegetallen");
while ($row = mysqli_fetch_assoc($result))
{
$ikhadingezetArray[$i]['getallen'] = $row['getal'];
$ikhadingezetArray[$i]['hoevaakingezets'] = $row['hoevaakingezet'];
$i++;
}
foreach($ikhadingezetArray as $value)
{
echo $value . "<br>";
}
My problem is that the foreach only echos "Array", not the values within the array.
And then I have to check if $teinsertengetal is in the array (the field "getal" in $ikhadingezetArray). If yes; I want the value of "hoevaakingezet" from the same row number of the array.
I hope you understand what I mean. Maybe it's not the best way I could do this?
Thank you in advance!
edit: the echo is just to check if the right values were inserted in the array.
For example:
Table "ingezettegetallen"
getal
hoevaakingezet
6
2
48
4
$teinsertengetal = 48
Now I would like check if 48 is in the column "getal". If yes (and it is in this example) I would like to store the value "4" in a variable (like $hoevaakingezetdus).
Put the check in the query, rather than fetching the entire table.
$stmt = $conn->prepare("
SELECT hoevaakingezet
FROM ingezettegetallen
WHERE getal = ?");
$stmt->bind_param("s", $teinsertengetal);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['hoevaakingezet'] . "<br>";
}

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

Setting PHP variables from Database Using MYSQL

Looking to select multiple values from the database and echo with PHP. (Newbie)
For instance:
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 4
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 5
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 6
How would I set the variables.. something along the lines of this using MYSQLi for multiple variables?
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$variable = $row["subcheckr"];
Truly appreciate any help.
Yes. Though if your query returns multiple rows, you'll need to use:
while ($row = mysqli_fetch_assoc($result))
{
//do something here
}
you need to make a loop for , foreach or a while loop
ex
while ($row = mysqli_fetch_assoc($result))
{
}
This should do it. First you need to connect, then you build your query. If query fails display an error so you know what went wrong. Then build your data array and use it.
$db = mysql_connect("localhost", "mysql_user", "mysql_password");
$sqlStremail = "SELECT `subcheckr`
FROM `login`
WHERE `username` = '".$u."'"; //needs to be concatenated
$result = mysql_query($sqlStremail, $db);
if(!$result) {
echo "query failed:". mysql_error();
exit;
}
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data = $row;
}
echo $data['sponsor'];
echo $data['contact'];
echo $data['script'];
//etc

PHP loop increment

I have a PHP loop generating a dataset for a chart. It queries two fields I have in a database table.
<?php
$server = "myserver:1234";
$user="dbuser";
$password="userpass";
$database = "dbname";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
$query = "SELECT X, Y FROM dbtable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($row['X'],$row['Y']);
}
$final = json_encode($dataset1,JSON_NUMERIC_CHECK);
?>
Currently data in X is meaningless (it's actually an ID column), and a number increment of 1 starting at 1 will be more useful. This is because I only want to plot a line chart, where X values are fixed. ID would be fine but the values put distracting axis labels on my chart.
How can I use PHP to generate this instead of the database select that I currently have?
Many thanks:)
Declare a variable outside your loop and increment it on each iteration:
$i = 1;
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($i, $row['Y']);
$i++;
}

Combining results of multiple if statements in php

I have a php file with two mysql queries and an if statement for each query. I'd like the final output to combine the two results and separate with a comma. Right now, the first if statement is working, but the second is not.
$result = mysql_query("SELECT round(AVG(cop),1) AS 'avg_cop' FROM table WHERE timestamp >= subdate((select max(timestamp) from table), interval 1 week)");
if ($result < 3.41)
{
$ret = "example text 1";
} else {
$ret = "na";
}
$result1 = mysql_query("SELECT round(AVG(temp),1) AS 'avg_temp' FROM table WHERE timestamp >= subdate((select max(timestamp) from table), interval 1 week)");
if ($result1 < 53)
{
$ret1 = "example text 2";
} else {
$ret1 = "na";
}
echo $ret.", ".$ret1;
In this instance, I know that the first query results in a "1.1" value and the second results in a "69.4" value. But, the final result I get is "example text 1, example text 2" when it should be "example text 1, na". Any ideas on what I'm doing wrong?
mysql_query doesn't return the row itself, it returns a resource that you need to pass into a function like mysql_fetch_array() or mysql_fetch_assoc() to deal with the table result; you can't just simply use the return value from mysql_query.
It would also probably be better if you just combined the SQL queries into one.
$result = mysql_query("SELECT round(AVG(cop),1) AS 'avg_cop', round(AVG(temp),1) AS 'avg_temp' FROM table WHERE timestamp >= subdate((select max(timestamp) from table), interval 1 week)");
$row = mysql_fetch_assoc($result);
if ($row['avg_cop'] < 3.41)
{
$ret = "example text 1";
} else {
$ret = "na";
}
if ($row['avg_temp'] < 53)
{
$ret1 = "example text 2";
} else {
$ret1 = "na";
}
echo $ret.", ".$ret1;
$result and $result1 are currently strings. You want to add:
$result = mysql_query("SELECT ... // unchanged");
$result = floatval($result)
if ($result < 3.41)
and for $result1
$result1 = mysql_query("SELECT ... // unchanged");
$result1 = floatval($result1)
if ($result1 < 53.0) // note the addition of the .0 to compare one float to another
Do not use MYSQL it has deprecated since PHP 5, use MYSQLi or PDO instead; they are much safer a provide you with improved features.
It is also good pratice to assign a null value to a PHP variable before assigning it a value, especially in this case ($ret ="" then you may change the value).
Finally, the results from mysql_query() is a resource, you need to iterate through it to get the proper values:
while ($row = mysql_fetch_assoc($result)):
//Do something with $row['avg_temp'];
endwhile;
Hope this helps!

Categories