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>";
}
Related
So I have fetched data from a MySQL database and I want to assign it to a variable based on an nth row. Only the bottom three rows are filtered and I want to assign values from the firs and last row to two variables.
$sql3 = "SELECT * FROM login_attempts WHERE login_attempt_user_id=? AND login_attempt_result=? ORDER BY login_attempt_id DESC LIMIT 3;";
$stmt3 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt3, $sql3)) {
echo 6;
exit();
} else {
mysqli_stmt_bind_param($stmt3, "ss", $login_attempt_user_id, $login_attempt_success);
mysqli_stmt_execute($stmt3);
$result2 = mysqli_stmt_get_result($stmt3);
if (mysqli_num_rows($result2) > 0) {
while ($row2 = mysqli_fetch_assoc($result2)) {
$test1 = $row2['login_attempt_time'][0];
$test2 = $row2['login_attempt_time'][2];
echo $test1.$test2;
exit();
}
} else {
//echo 4;
exit();
}
}
The section of code is within the while loop and I realize that what I am attempting is for arrays. I want to do something similar to achieve my goal.
My code is not assigning the database entry to the variable: $test = $row2['login_attempt_time'] assigns the last value of the fetched row, however $test = $row2['login_attempt_time'][0] only returns the value 1.
Would anyone please be able to help with this?
Fetch all (three) rows into an array (2-dimensional) with mysqli::fetch_all(). Then get the first and the last elements (rows) with reset() and end().
Change
while ($row2 = mysqli_fetch_assoc($result2)) {
$test1 = $row2['login_attempt_time'][0];
$test2 = $row2['login_attempt_time'][2];
echo $test1.$test2;
exit();
}
to
$data = $result2->fetch_all(MYSQLI_ASSOC);
$variable1 = reset($data); // first row
$variable2 = end($data); // last row
Remember, this mysqli_fetch_assoc($result2)) will fetch one row from the database. So the first time, $row2 will be the contents of the first row, the second time $row2 is the second row, etc. Perhaps add a counter to the loop to know when to populate $test1 and $test2, as with an if condition.
I am using the code below to return value from sql but the value is displayed 2 times.
$cc=mysqli_connect($server,$user,$pass);
mysqli_select_db($cc,$database);
$sql = "SELECT b_id FROM ``ub_per`` WHERE ``b_email`` = '$mail'";
$res = mysqli_query($cc,$sql);
$row = mysqli_fetch_array($res);
foreach($row as $value){
echo($value);
}
I think the answer is a little more complex than that.
So the row $row = mysqli_fetch_array($res); will return an array, I think if you check there will be 2 items in it.
Looking like this
$row[0] = id;
$row['b_id'] = id;
now you do
foreach($row as $value){
echo($value);
}
So will echo id out twice.
Use
$row = mysqli_fetch_array($res,MYSQLI_ASSOC);
To get you what you want.
It is because query gives you 2 results(rows).
Try:
echo '<pre>';
print_r($row);
And you will see if there are more than 1 rows in results.
$search = htmlspecialchars($_GET["s"]);
if(isset($_GET['s'])) {
// id index exists
$wordarray = explode(" ",$search);
$stringsearch = implode('%',$wordarray);
echo $stringsearch;
echo ",";
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
if (!empty($result)) {
echo sizeof($result);
echo ",";
Database has 3 rows with titles test,pest,nest with corresponding id's 1,2,3. when i request domain.com/?s=est
it echos something like this
est,2,
Now when i checked $result[0] and $result[1], $result[0] echoed 1 and $result[1] didn't echo anything. When I use foreach function, it is taking only value of $result[0]
and $result should be array of all the three indexes.
I cannot find any mistake,
when i type the same command in sql console it works, somebody help me, thanks in advance.
The problem is, if you're expecting multiple rows, then don't do this:
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
This only fetches the first row, you need to loop it to advance the next pointer and get the next following row set:
$result = $conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%' ");
while($row = $result->fetch_array()) {
echo $row[0] . '<br/>';
// or $row['ID'];
}
Sidenote: Consider using prepared statements instead, since mysqli already supports this.
RESOLVED
I have used the answer from alfasin, but as that gave me WAY too much information, i wrote a little script to just get the field names. As the field names apeared first, it was rather simple:
$here = array();
$SQL = "SHOW COLUMNS FROM User";
foreach($conn->query($SQL) as $row) {
$here[] = $row[0];
}
echo '<pre>';print_r($here);echo '<pre>';
This left me with the new array $here containing the column names, hope this helps someone in the future :)
Original question:
Let me clarify a bit, I have a mysql table and I'm trying to select * from it, and display the result in an html list <ol>. I can manage to grab the row data JUST FINE, but I cannot for the life of me figure out how to grab the table column names, in order to match them up with the row, respectively. this is my code that is grabbing the row data:
//get those results
$sql = "SELECT DISTINCT *
FROM User
WHERE Owner = '".$owner."'";
foreach($conn->query($sql) as $row) {
//split array in half
$hax = count($row);
$halfHax = $hax / 2;
//set up a for loop to give results
$u = 1;
for($i = 2; $i <= $halfHax; $i++){
echo $row[$u].'<br>';
$u++;
}
}
this is giving me all the result where Owner == $owner just like it should, but I would like the column names to list with those, I could hard-code it out, but more columns may be added/changed so I would rather not. Any ideas?
Try:
SHOW COLUMNS FROM mytable
http://dev.mysql.com/doc/refman/5.0/en/show-columns.html
Fetch rows as associative arrays in order to keep your column names as array keys.
Here's my suggestion:
$sql = "SELECT DISTINCT * FROM User WHERE Owner = :owner";
$sth = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':owner' => $owner);
while($row=$sth->fetch(PDO::fetch_assoc) as $row) {
//split array in half
$hax = count($row);
$halfHax = $hax / 2;
//set up a for loop to give results
foreach ($row as $key => $value) {
echo $key.'='.$value.'<br />';
}
}
To just list the column names:
array_keys($row);
Please refer to SHOW COLUMNS at the MySQL Reference if you want more information about the columns.
But I'd suggest using mysqli_fetch_assoc and then using foreach (array_expression as $key => $value) to get the column name and it's value, for each row.
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']).