I have a php code which insert questions and answers for a quiz into a mysql database and for each answer a specifically tinyint number. With this method I can choose which one is the correct answer by allocating the number 1 to it and 0 to the rest of them. What I want is to can allocate to the wrong answers the numbers 2, 3 and 4, not 0 to all. I hope you understood. My English is not so good. Thank you very much !
My code:
// Question query
$query = "INSERT INTO `questions`(question_number, text)
VALUES('$question_number', '$question_text')";
// Run query
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
// Validate insert
if ($insert_row) {
foreach ($choices as $choice => $choice_text) {
if($choice_text != '') {
if($correct_choice == $choice) {
$is_correct = 1;
} else{
$is_correct = 0;
}
Why don't you specify the wrong answer when it's not correct?
if($choice_text != '') {
if($correct_choice == $choice) {
$is_correct = 1;
} else{
$is_correct = $choice;
}
Related
I want to delete top first row from table in firebase Database when no. of rows reach to 50.
I can search this lot of time but still not found. Anyone tell that how I can do this.
Through this technique
$searchdata = "Data";
$fetchdata = $database->getReference($searchdata)->getValue();
$found = 0;
$array=0;
if($fetchdata > 0)
{
foreach($fetchdata as $Key => $row)
{
if($found == 0)
{
$del = "Data/".$Key;
$DelRef = $database->getReference($del)->remove();
$found=1;
}
else
{
break;
}
}
}
I made the script to do what is expected, so it work ok but there must be a more elegant way to achieve the same result. I know that using switch will make it look nicer but not sure if the result will be the same as the 'default:' behavior:
This is the section of the script i want to refactor:
foreach ($free_slots as $val) { // here i am looping through some time slots
$slot_out = $free_slots[$x][1];
$slot_in = $free_slots[$x][0];
$slot_hours = $slot_out - $slot_in;
// tasks
if ($slot_out != '00:00:00') {
// Here i call a function that do a mysql query and
// return the user active tasks
$result = tasks($deadline,$user);
$row_task = mysql_fetch_array($result);
// HERE IS THE UGLY PART <<<<<----------------
// the array will return a list of tasks where this current
// users involved, in some cases it may show active tasks
// for other users as the same task may be divided between
// users, like i start the task and you continue it, so for
// the records, user 1 and 2 are involved in the same task.
// The elseif conditions are to extract the info related
// to the current $user so if no condition apply i need
// to change function to return only unnasigned tasks.
// so the i need the first section of the elseif with the
// same conditions of the second section, that is where i
// actually take actions, just to be able to change of
// change of function in case no condition apply and insert
// tasks that are unassigned.
if ($row_task['condition1'] == 1 && etc...) {
} else if ($row_task['condition2'] == 1 && etc...) {
} else if ($row_task['condition3'] == 1 && etc...) {
} else if ($row_task['condition4'] == 1 && etc...) {
} else {
// in case no condition found i change function
// and overwrite the variables
$result = tasks($deadline,'');
$row_task = mysql_fetch_array($result);
}
if ($row_task['condition1'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition2'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition3'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition4'] == 1 && etc...) {
} else {
echo 'nothing to insert</br>';
}
}
}
Basically i run the else if block twice just to be able to change of function in case nothing is found in the first loop and be able to allocate records unassigned.
I haven't changed the functionality of your code, but this is definitely a lot cleaner.
The main problem was that your logic for your if/else statements was confused. When you're writing:
if($a == 1){ } else if($b == 1){ } else if($c == 1){ }else{ //do something }
You're saying If a is 1 do nothing, if b is 1 do nothing, if c is 1 do nothing, but if all of those did nothing, do something when you can just say if a is not 1 and b is not 1 and c is not 1, do something.
I wasn't too sure on your second if statements, but generally it's not good to have an if else with no body within it. However, if the "insert into database" comment does the same thing, you can merge the 3 if statements that do the same code.
I hope i've cleared a few things up for you.
Here's what I ended up with:
foreach ($free_slots as $val) { // here i am looping through some time slots
$slot_out = $free_slots[$x][1];
$slot_in = $free_slots[$x][0];
$slot_hours = $slot_out - $slot_in;
// tasks
if ($slot_out != '00:00:00') {
$result = tasks($deadline, $user);
$row_task = mysql_fetch_array($result);
if (!($row_task['condition1'] == 1 || $row_task['condition2'] == 1 || $row_task['condition3'] == 1 || $row_task['condition4'] == 1)) {
$result = tasks($deadline,'');
$row_task = mysql_fetch_array($result);
}
if ($row_task['condition1'] == 1 && etc...) {
// insert into database
} else if ($row_task['condition2'] == 1) {
// insert into database
} else if ($row_task['condition3'] == 1) {
// insert into database
} else if ($row_task['condition4'] == 1) {
} else {
echo 'nothing to insert</br>';
}
}
}
There is an error while i insert "3 + 1 room" or update description area with "3 + 1 room" in MySQL database.
I saw there is no addition sign "+" in MySQL log (data inserted in database)
UPDATE testtable set status='0',title='3 1 room',
description='3 1 Daire. 1 Balkon kapalı.' WHERE id='60';
create table testtable ( id int(11), status tinyint(4), title varchar(20),
description text) ENGINE=InnoDB DEFAULT CHARSET=utf8
php file
$baglanti=new PDO("mysql:host="localhost";dbname="test";charset=utf8",$us
ername,$passwd) or die("error");
$val=$baglanti->exec("UPDATE testtable set status='0',title='$title',
description='$dest' WHERE ad_no='$ad_no' ");
return $val;
What should I do?
EDIT
update.php
<?php
include("database.php");
$fields = array();
$values=array();
$fvalue=$_POST['id'];
$table=$_POST['table'];
foreach ($_POST as $key => $value) {
if( $key!='table' && $key!='id' && $key!='alan'){
if( strpos($key,"date")){
$datet=new DateTime($value);
$value=$datet->format('Y-m-d');
}
array_push($fields,$key);
array_push($values,$value);
}
}
$alan=$_POST['alan'];
$ID=Updt($table,$fields,$values,$alan,$fvalue);
if($ID!=0){
echo $ID;
}
?>
database.php
<?php
$baglanti=new PDO("mysql:host="localhost";dbname="test";charset=utf8",$us
ername,$passwd) or die("error");
#UPDATE
function Updt($table,$set,$value,$field,$fvalue){
$bag=$GLOBALS['baglanti'];
$sts='';
if(is_array($set)){
for ($i=0; $i < count($set); $i++) {
$sts.=$set[$i]."='".$value[$i]."',";
}
$sts=rtrim($sts,",");
}else{
$sts=$set."='".$value."'";
}
$val=$bag->exec("UPDATE $table set $sts WHERE $field='$fvalue'");
return $val;
}
?>
this one, programmers wrote code. I try to take question parts from all code. There were lots of codes in file.
My guess is that you are not generating the query you think you are.
This should allow you to see the query.
I have also added some error checking, that really should be used in this code.
I have amended the connection line as I am sure a newline in the middle of the $username variable will cause an error.
database.php
<?php
try {
$baglanti = new PDO("mysql:host=localhost;dbname=test;charset=utf8",
$username,$passwd);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
#UPDATE
function Updt($table,$set,$value,$field,$fvalue){
$bag = $GLOBALS['baglanti'];
$sts='';
if(is_array($set)){
for ($i=0; $i < count($set); $i++) {
$sts.=$set[$i]."='".$value[$i]."',";
}
$sts=rtrim($sts,",");
}else{
$sts=$set."='".$value."'";
}
$sql = "UPDATE $table set $sts WHERE $field='$fvalue'";
echo $sql; // you can comment this line out when you are sure the SQL is good
$val = $bag->exec($sql);
return $val;
}
?>
update.php
Small amendment here just so you know whats actually being returned from the function is a count and not a row ID. It could also be FALSE, indicating an error occured in the Updt() function in the query.
<?php
include("database.php");
$fields = array();
$values=array();
$fvalue=$_POST['id'];
$table=$_POST['table'];
foreach ($_POST as $key => $value) {
if( $key!='table' && $key!='id' && $key!='alan'){
if( strpos($key,"date")){
$datet=new DateTime($value);
$value=$datet->format('Y-m-d');
}
array_push($fields,$key);
array_push($values,$value);
}
}
$alan=$_POST['alan'];
//$ID=Updt($table,$fields,$values,$alan,$fvalue);
// this is not an ID it is a coumt of the number or rows
// updated by the Updt() function
$cnt = Updt($table,$fields,$values,$alan,$fvalue);
if ( $cnt === FALSE ) {
// then we had an error in Updt()
print_r($baglanti->errorInfo(), true);
exit;
}
if($cnt != 0){
echo 'Rows updated = ' . $cnt;
}
?>
I have to mention this as others will if I dont. Your code is open to SQL Injection you should really be using prepared statements. Maybe you should mention this to the Programmers you mentioned. Maybe you should also not assume everything they wrote was done correctly.
This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 8 years ago.
I am trying to send query to mysql to insert some values into a table , this is not the first time I do this stuff and this is what making me getting crazy !
when I am printing the query it looks like this :
INSERT INTO hc_family_receive_relief
(hc_family_id,hc_received_kind,hc_received_date,hc_received_month,hc_received_year)
VALUES ('89','��� ��������','30','5','2014')
This is the first time I face this issue , what is the reason of it ?
I even try to save the PHP file as UTF-8 , UTF-8 with out BOM , Arabic characters still not inserted to the table ! .
the following is the function that I used to create the query dinamicly from $_POST array :
function add_family_recieve_relief($array)
{
if(empty($array))
return NULL;
$i = 0;
$titles = array();
$values = array();
$query = "INSERT INTO hc_family_receive_relief ";
foreach($array as $key => $value)
{
if($i == 0)
{
$titles[count($titles)] = "($key,";
$values[count($values)] = "('".$value."',";
}
if($i < count($array) - 1 && $i > 0)
{
$titles[count($titles)] = "$key,";
$values[count($values)] = "'".$value."',";
}
if($i == count($array) - 1)
{
$titles[count($titles)] = $key.") VALUES ";
$values[count($values)] = "'".$value."')";
}
$i++;
}
foreach($titles as $tvalue)
$query .= $tvalue;
foreach($values as $vvalue)
$query .= $vvalue;
echo $query;
$qresult = mysql_query($query);
if(!$qresult)
return False;
else return True;
}
and this is the page that recive $_POST and pass it to function add_family_recieve_relief:
<?
require_once('../db.php');
require_once('familyReliefAPI.php');
if($_POST['addfamilyrelief'])
{
if(empty($_POST['hc_family_id']) || !is_numeric($_POST['hc_family_id']))
die('<center><h4><font color="red">خطأ في المعالجة , الرقم المميز للعائلة غير موجود !</font></h4></center>');
$family_id = $_POST['hc_family_id'];
array_pop($_POST);
$addfrr = add_family_recieve_relief($_POST);
if(!$addfrr)
die('<center><h4><font color="red">مشكلة في الاضافة , الرجاء التأكد من المعلومات أو الاتصال</font></h4></center>');
else {
//print_r($_POST);
}
}
?>
also I make SET NAMES utf-8 query in the connection page to fix the character issues , but still not work ..
please HELP ME .. thanks
NOTE :
The query is getting true and insert all the values in table except the arabic field it leaves it empty !
Check the charset of the table which is present in the database
All day I've been trying to achieve the following with PHP:
Update: This is the code I'm using, please read the message in between
<?php
include ('acs_params.php');
$acs_value_based = array(25, 30, 35, 40, 45, 50, 60, 70);
$acs_types = array("$add_total","$done_total");
print_r($acs_id);
foreach ( $acs_value_based as &$value ) {
foreach ( $acs_types as &$counters) {
if ($counters >= $value) {
if ($acs_types[0] == $counters) {$acs_types1 = '1'; $acs_name = 'Tasker'; $acs_action = 'adding';}
if ($acs_types[1] == $counters) {$acs_types1 = '2'; $acs_name = 'Completer'; $acs_action = 'completing';}
if ($value == '25') { $acs_lvl = '1'; $acs_id = '25';}
if ($value == '30') { $acs_lvl = '2'; $acs_id = '30';}
if ($value == '35') { $acs_lvl = '3'; $acs_id = '35';}
$acs_exists = $acs_types1 . $acs_id;
Over here it should check if this array print_r($acs_id); contains the value of
$acs_exists. if the value already exists the following code should not be executed,
instead, the script should start again at the beginning but then with the second value of
the array print_r($acs_id);. It the value is not existing yet, then continue with the queries. (I hope my goal is clear).
mysql_query("INSERT INTO users_log(id, log, userid, date, points, action) VALUES
(id, 'achievement 1', '$username', '$currenttime', '0', '8') ");
mysql_query("INSERT INTO users_achievements(id, userid, acs_id, date) VALUES
(id, '$username', '$acs_types1$acs_id', '$currenttime') ");
?>
foreach ($acs_id as $item) {
if ($item == $acs_exist) continue;
// continue with the script (query etc)
}
Is that what you're after?
This sounds to simple, but I'll give it a shot:
// if $acs_exist is not in the array $acs_id, execute script, otherwise do nothing
if(!in_array($acs_exist, $acs_id)) {
// do whatever you want
}
I'm still poking in the dark here …
foreach($acs_id => $id) {
if($acs_id == $acs_exist) { // already exists
} else { // does not exist yet, insert into db
// your code: INSERT INTO table (column, …) VALUES(:acs_id, …)
}
}