In my MySQL table (userdata) there's a column named "options". In that column user responses are stored after they complete a quiz.
Sample data pertaining to a user is given below:
{"correctness":{"question_id_209":false,"question_id_208":true,"question_id_207":true,"question_id_206":false,"question_id_205":true},"user_answered":{"question_id_209":"830","question_id_208":"826","question_id_207":"822","question_id_206":"818","question_id_205":"815"},"passed_time":"13 seconds","user_points":3,"max_points":5,"attributes_information":[],"calc_method":"by_correctness"}
Now I want to search this array for the word "true" and want to count the word.
I started with this, but don't know what to do next:
$query="SELECT options FROM userdata WHERE user_id=1";
$result= mysqli_query($conn,$query);
If you want to only count how many correct answers the user had for display purposes, here is what you should do following your example:
$row = mysqli_fetch_assoc($result);
$data = json_decode($row['options'], true);
$correctAnswers = array_filter($data['correctness'], function($question) {
return $answer === true;
});
$total = count($correctAnswers);
But if you want to do a SQL query, then it would be more complicated. For that you might want to take a look at this page:
https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html
I hope it helps.
Related
I am trying to read an compare values from mysqli query but unsuccessfully.
This is example of my code:
$sql = "SELECT team, won, lost, points, goals_for, goals_agn FROM teaminfo WHERE tour_id=5 ORDER BY points DESC, (goals_for - goals_agn) DESC, goals_for DESC ;";
$query = $this->db_connection->query($sql);
so its simple sql query where I grab all teams from teaminfo DB and I want to compare them according to certain criteria (points, goal scored...) to see which team will go into the next phase of the competition.
Its is simple to print ALL values with something like loop:
while ($team=mysqli_fetch_array($query)) {... some code ...}
But I dont need this. I want to access only few of them and compare them. For example:
//Compare 3rd team points from $query with 4th team points from $query
If ($team[3]['points']==$team[4]['points'])
{
I would do something..
} else ....
I just want "transform" $query so I can use all data from it manually. I tried some stuff from php.net for fetching data but like I said, all was unsuccessfull.
You could put all the data in an array and than work with that.
$teams = array();
while ($team=mysqli_fetch_array($query)) {
$teams[$team['team']] = $team;
}
Then you can access them via $teams['teamname']
if($teams['teamA']['points'] == $teams['teamB']['points']){
// do something
}
its possible to just use
$teams[] = $team;
To fill the array. But I'd recommand an associative filling as that makes it easiert to access the data for a team. With only a numeric entry you'd have to check for their names if you want to use data of specific teams.
I'm having a little problem with the codes given below. When I'm using the name="staff_number[]" then it insert the record with everything ok even if it is already in the database table and when i use name="staff_number" it does check the record and also give me alert box but when insert the record if it is not in the database it stores only the first number of the staff number like the staff no is 12345 it stores only 1. can anyone help in this record i think there is only a minor issue what I'm not able to sort out.
PHP Code:
<select placeholder='Select' style="width:912px;" name="staff_number[]" multiple />
<?php
$query="SELECT * FROM staff";
$resulti=mysql_query($query);
while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['staff_no']?>"><?php echo $row['staff_name']?></option>
<?php } ?>
</select>
Mysql Code:
$prtCheck = $_POST['staff_number'];
$resultsa = mysql_query("SELECT * FROM staff where staff_no ='$prtCheck' ");
$num_rows = mysql_num_rows($resultsa);
if ($num_rows > 0) {
echo "<script>alert('Staff No $prtCheck Has Already Been Declared As CDP');</script>";
$msg=urlencode("Selected Staff ".$_POST['st_nona']." Already Been Declared As CDP");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Insert Query
$st_nonas = $_POST['st_nona'];
$t_result = $_POST['st_date'];
$p_result = $_POST['remarks'];
$arrayResult = explode(',', $t_result[0]);
$prrayResult = explode(',', $p_result[0]); $arrayStnona = $st_nonas;
$countStnona = count($arrayStnona);
for ($i = 0; $i < $countStnona; $i++) {
$_stnona = $arrayStnona[$i];
$_result = $arrayResult[$i];
$_presult = $prrayResult[$i];
mysql_query("INSERT INTO staff(st_no,date,remarks)
VALUES ('".$_stnona."', '".$_result."', '".$_presult."')");
$msg=urlencode("CDP Staff Has Been Added Successfully");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Your $_POST['staff_number'] is actually an array.
So you have to access it like $_POST['staff_number'][0] here, 0 is a index number.
If the name of select is staff_number[] then $prtCheck will be a array so your check query must be in a loop to make sure your check condition.
if the name is staff_number then the below code is fine.
The answer of amit is right but I will complete it.
Your HTML form give to your PHP an array due to the use of staff_number[] with [] that it seems legit with the "multiple" attribute.
So you have to loop on the given values, you do it with a for and a lot of useless variables without really checking it. From a long time, we have the FOREACH loop structure.
I could help you more if i know what is the 'st_nona', st_date' and 'remarks' values.
According to your question you are getting difficulty in storing the data. This question is related to $_POST array.
Like your question we have selected following ids from the select : 1,2,3,4
It is only storing 1.
This is due to you have not used the loop when inserting the data.
Like below:
<?php
foreach($_POST['staffnumber'] as $staffnumber){
$query=mysql_query("select * from staff where staff_number =".$staffnumber);
if(mysql_num_rows($query)>0){
//action you want to perform
}else{
//action you want to perform like entering records etc. as your wish
}
}
?>
And I would like to suggest you that use the unique keys in database for field and use PHP PDO for database, as it is secure and best for OOPs.
Let me know if you have any queries.
So i have this so far..
if(isset($_POST['Decrypt']))
{
$dbinary = strtoupper($_POST['user2']);
$sqlvalue = "SELECT `value` FROM `license` WHERE `binary` = '$dbinary'";
$dvalue = mysql_query($sqlvalue) or die(mysql_error());
$dvalue = mysql_fetch_array($dvalue);
$dvalue['value'];
}
I have a field where the user enters a binary code which was encrypted. (The encrypt part works). This is supposed to retrieve the value from the database. When ever i do it, instead of the value showing up, it says "Array".
Please help me out.
This is because you can't just echo an array. You need to use functions like var_dump(); or print_r();
looks like you have more than one row in your table matching criteria. Try using while loop to retrieve data.
while($row = mysql_fetch_assoc($dvalue)){
//$row['value'];
}
hello i want to create function with returning data, for example when i have the function advert i want to make it every time show what i need, i have the table id, sub_id, name, date, and i want to create the function that i can print every time what i need advert(id), advert(name), i want to make it to show every time what i need exactly and i want to save all my result in array, and every time grab the exactly row that i want
<?php
function advert($data){
$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
$data = array(
'id' => $row['id']
);
}
return $data;
}
echo advert($data['id']);
?>
but my result every time is empty, can you help me please?
There are so many flaws in this short piece of code that the only good advice would be to get some beginners tutorial. But i'll put some effort into explaining a few things. Hopefully it will help.
First step would be the line function advert($data), you are passing a parameter $data to the method. Now later on you are using the same variable $data in the return field. I guess that you attempted to let the function know what variable you wanted to fill, but that is not needed.
If I understand correctly what you are trying to do, I would pass in the $id parameter. Then you can use this function to get the array based on the ID you supplied and it doesnt always have to come from the querystring (although it could).
function advert($id) {
}
Now we have the basics setup, we want to get the information from the database. Your code would work, but it is also vulnerable for SQL injection. Since thats a topic on its own, I suggest you use google to find information on the subject. For now I'll just say that you need to verify user input. In this case you want an ID, which I assume is numeric, so make sure its numeric. I'll also asume you have an integer ID, so that would make.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
}
Then I'll make another assumption, and that is that the ID is unique and that you only expect 1 result to be returned. Because there is only one result, we can use the LIMIT option in the query and dont need the while loop.
Also keep in mind that mysql_ functions are deprecated and should no longer be used. Try to switch to mysqli or PDO. But for now, i'll just use your code.
Adding just the ID to the $data array seems useless, but I guess you understand how to add the other columns from the SQL table.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
$query = mysql_query("SELECT * FROM advertisement WHERE id = $id LIMIT 1");
$row = mysql_fetch_assoc($query);
$data = array(
'id' => $row['id']
);
return $data;
}
Not to call this method we can use the GET parameter like so. Please be advised that echoing an array will most likely not give you the desired result. I would store the result in a variable and then continue using it.
$ad = advert($_GET['id']);
if (!is_array($ad)) {
echo $ad; //for sql injection message
} else {
print_r($ad) //to show array content
}
Do you want to show the specific column value in the return result , like if you pass as as Id , you want to return only Id column data.
Loop through all the key of the row array and on matching with the incoming Column name you can get the value and break the loop.
Check this link : php & mysql - loop through columns of a single row and passing values into array
You are already passing ID as function argument. Also put space between * and FROM.
So use it as below.
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$data."'");
OR
function advert($id)
{
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$id."'");
$data = array();
while($row = mysql_fetch_assoc($query))
{
$data[] = $row;
}
return $data;
}
Do not use mysql_* as that is deprecated instead use PDO or MYSQLI_*
try this:
<?php
function advert($id){
$data= array();
//$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
array_push($data,$row['id']);
}
return $data;
}
var_dump($data);
//echo advert($data['id']);
?>
I'm new to PHP and SQL, but I need a way to store the result of an SQL Query into a variable.
The query is like this:
$q = "SELECT type FROM users WHERE username='foo user'";
$result = pg_query($q);
The query will only return one string; the user's account type, and I just need to store that in a variable so I can check to see if the user has permission to view a page.
I know I could probably just do this query:
"SELECT * FROM users WHERE username='foo user' and type='admin'";
if(pg_num_rows($result) == 1) {
//...
}
But it seems like a bad practice to me.
Either way, it would be good to know how to store it as a variable for future reference.
You can pass the result to pg_fetch_assoc() and then store the value, or did you want to get the value without the extra step?
$result = pg_query($q);
$row = pg_fetch_assoc($result);
$account_type = $row['type'];
Is that what you are looking for?
Use pg_fetch_result:
$result = pg_query($q);
$account_type = pg_fetch_result($result, 0, 0);
But on the other hand it's always good idea to check if you got any results so I'll keep the pg_num_rows check.