I'm trying to show a profile completeness bar on the users account and the progress bar is showing but it's not adding the number values in order to calculate the percentage of completed fields ie:
if($row['title'] != '')
$completedTitle = 20;
My shortened code is as follows:
<?php
$result = mysql_query("SELECT title,name,surname,identityno,gender FROM cic_candidates WHERE id='$id' LIMIT 1");
while($row = mysql_fetch_assoc($result))
$maximumPoints = 100;
{
if($row['title'] != '')
$completedTitle = 20;
if($row['name'] != '')
$completedName = 20;
if($row['surname'] != '')
$completedSurname = 20;
if($row['identityno'] != '')
$dcompletedIdentityno = 20;
if($row['gender'] != '')
$completedGender = 20;
}
$percentage = ($dcompletedTitle+$completedName+$completedSurname+$completedIdentityno+$completedGender)*$maximumPoints/100;
echo "".$percentage."%";
?>
The percentage shows in the echo but the total is wrong - it's not taking the values of 20 points for each field that is completed and including them in the "addition" part of the percentage calculation. Please can you tell me where I'm going wrong - I've been trying to figure this out for 4 days and have googled this and read over 2000 forums but can't find the answer. Any help would be greatly appreciated.
I think you are getting it all wrong from your condition, try this... it worked for me
$sql = "SELECT title,name,surname,identityno,gender FROM cic_candidates WHERE id='{$id}' LIMIT 1";
$result = $DBconnection->query($sql);
$maxvalue = 100;
$point = 0;
if ($result) {
while($row = $result->fetch_assoc()){
if($row['title'] != ''){
$point1 = $point+20;
}elseif($row['title'] == ''){
$point1 = $point+=0;
}
if($row['name'] != ''){
$point2 = $point+20;
}elseif($row['name'] == ''){
$point2 = $point+=0;
}
if($row['surname'] != ''){
$point3 = $point+20;
}elseif($row['surname'] == ''){
$point3 = $point+0;
}
if($row['identityno'] != ''){
$point4 = $point+20;
}elseif($row['identityno'] == ''){
$point4 = $point+0;
}
if($row['gender'] != ''){
$point5 = $point+=20;
}elseif($row['gender'] == ''){
$point5 = $point+0;
}
// otherwise
}
}else{
echo "error completing query";
}
$pint = $point1+$point2+$point3+$point4+$point5;
$percentage = ($pint*100)/100;
echo $percentage."%";
use {} around single quotes in query
<?php
// fisrt select database
$result = mysql_query("SELECT title,name,surname,identityno,gender FROM cic_candidates WHERE id='{$id}' LIMIT 1");
//use of MYSQL_QUERY is deprecated so don't use it
//use mysqli_query instead of mysql_query
if (!$result) {
echo "Could not successfully run query " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while($row = mysql_fetch_assoc($result))
$maximumPoints = 100;
$point = 0;
{
if($row['title'] != '')
$point+=20;
if($row['name'] != '')
$point+=20;
if($row['surname'] != '')
$point+=20;
if($row['identityno'] != '')
$point+=20;
if($row['gender'] != '')
$point+=20;
}
$percentage = ($point*$maximumPoints)/100;
echo $percentage."%";
?>
Related
I have 2 function, insertInto for inserting data from ma array in a Mysql database, and checkRow where I check if the current row from my array already exists. The structure of the array tableArray is $tableArray["Tabelle2"][number of row][number of column]. However, always when I refresh the page it inserts more rows in the database and avoid to check if the row already exists.
the function insertInto:
function insertInto($i, $tableArray, $conn){ //insert into db
$dateFormated = split('/', $tableArray["Tabelle2"][$i][3]);
$date = $dateFormated[2].'-'.$dateFormated[0].'-'.$dateFormated[1];
$insertInto = "insert into Excel(Arbeitsplatz, Auftragsart, Auftragsnummer, Datum, Tageszeit, Erklaerung, Beschreibung, AG, StdArt, Anwender)
values('".$tableArray["Tabelle2"][$i][0]."', '".$tableArray["Tabelle2"][$i][1]."', '".$tableArray["Tabelle2"][$i][2]."', '".$date."',
'".$tableArray["Tabelle2"][$i][4]."', '".$tableArray["Tabelle2"][$i][5]."', '".$tableArray["Tabelle2"][$i][6]."',
'".$tableArray["Tabelle2"][$i][7]."', '".$tableArray["Tabelle2"][$i][8]."', '".$tableArray["Tabelle2"][$i][9]."')";
if($conn->query($insertInto) === true){echo "Datensatz Nr. ".$i." wurde eingefuegt.<br />";}else{echo "Datensatz Nr. ".$i." wurde nicht eingefuegt.<br />";}
}
the function checkRow:
function checkRow($i, $tableArray, $conn){ //if(... == ...)
$count = "select count(*) from Excel;";
$res = $conn->query($count);
$row = $res->fetch_assoc();
$rowsNum = $row["count(*)"];
if($rowsNum == 0){
insertInto($i, $tableArray, $conn);
} else {
for($b = 1; $b <= $rowsNum; $b++){
$select = "select * from Excel where ExcelID = '".$b."'";
$result = $conn->query($select);
$row = $result->fetch_assoc();
if($tableArray["Tabelle2"][$i][0] == $row["Arbeitsplatz"] && $tableArray["Tabelle2"][$i][1] == $row["Auftragsart"] && $tableArray["Tabelle2"][$i][2] == $row["Auftragsnummer"] && $tableArray["Tabelle2"][$i][4] == $row["Tageszeit"] && $tableArray["Tabelle2"][$i][5] == $row["Erklaerung"] && $tableArray["Tabelle2"][$i][6] == $row["Beschreibung"] && $tableArray["Tabelle2"][$i][7] == $row["AG"] && $tableArray["Tabelle2"][$i][8] == $row["StdArt"] && $tableArray["Tabelle2"][$i][9] == $row["Anwender"]){
echo "Datensatz ist bereits vorhanden.<br />";
} else {
insertInto($i, $tableArray, $conn);
}
}
}
}
the loop where I call the function checkRow:
for($g = 1; $g <= count($tableArray["Tabelle2"]); $g++){
checkRow($g, $tableArray, $conn);
}
I solved it, the problem was in the function checkRow();, I always checked the current row from my array with 1 row in the Mysql database, and not all of them. By adding $counter, which counts always + 1 if the current row in the array is not the same as the row in the database, I solved the problem.
updated function checkRow:
function checkRow($i, $tableArray, $conn){ //if(... == ...)
$count = "select count(*) from Excel;";
$res = $conn->query($count);
$row = $res->fetch_assoc();
$rowsNum = $row["count(*)"];
$counter = 0;
if($rowsNum == 0){
insertInto($i, $tableArray, $conn);
} elseif($rowsNum > 0) {
for($b = 1; $b <= $rowsNum; $b++){
$select = "select * from Excel where ExcelID = '".$b."'";
$result = $conn->query($select);
$row = $result->fetch_assoc();
if($tableArray["Tabelle2"][$i][0] == $row["Arbeitsplatz"] && $tableArray["Tabelle2"][$i][1] == $row["Auftragsart"] && $tableArray["Tabelle2"][$i][2] == $row["Auftragsnummer"] && $tableArray["Tabelle2"][$i][4] == $row["Tageszeit"] && $tableArray["Tabelle2"][$i][5] == $row["Erklaerung"] && $tableArray["Tabelle2"][$i][6] == $row["Beschreibung"] && $tableArray["Tabelle2"][$i][7] == $row["AG"] && $tableArray["Tabelle2"][$i][8] == $row["StdArt"] && $tableArray["Tabelle2"][$i][9] == $row["Anwender"]){
echo "Datensatz ist bereits vorhanden.<br />";
} else {$counter++;}
}
if($counter == $rowsNum){
insertInto($i, $tableArray, $conn);
$counter = 0;
}
}
}
I have a form with multiple inputs which are my filters.
This is my code (not all of it, just the part I want to fix):
$req_resumo = '';
$req_status = '';
$req_usuario = '';
$n_req = 0;
$parametros = "";
// Checks which fields are filled and increases the number of filters for future usage
if (isset($_POST['usuario']) && $_POST['usuario'] != "") {
$req_usuario = $_POST['usuario'];
$n_req++;
}
if (isset($_POST['resumo']) && $_POST['resumo'] != "") {
$req_resumo = $_POST['resumo'];
$n_req++;
}
if (isset($_POST['status']) && $_POST['status'] != "") {
$req_status = $_POST['status'];
$n_req++;
}
// Then (there is some code between these parts)
if ($n_req > 0 && $funcao != 'usuario') $parametros.= " where ";
if ($req_usuario != "") {
$parametros.= " usuario = '$req_usuario' ";
if ($n_req > 1) $parametros.= " and ";
}
if ($req_resumo != "") {
$parametros.= " resumo = '$req_resumo' ";
if ($n_req > 1 && ($req_status != "") || ($req_data_inicial != "")) $parametros.= " and ";
}
if ($req_status != "") {
$parametros.= " status = '$req_status' ";
}
// This will create the query and add the parameters string at the end.
$tot = mysqli_query($con, "SELECT * FROM solicitacoes $parametros");
This code looks ugly, and even for me (begginer), it doesn't feels right, does not sounds like the way of coding.
So, is there any better and easier way of building this code?
Give this a try. From my testing locally (without db) looked right.
$n_req = 0;
$_POST['usuario'] = 'test';
$_POST['resumo'] = 'test2';
$_POST['status'] = 'test3';
if (!empty($_POST['usuario'])) {
$req_usuario = $_POST['usuario'];
$where[] = " usuario = ? ";
$params[] = $req_usuario;
$n_req++;
}
if (!empty($_POST['resumo'])) {
$req_resumo = $_POST['resumo'];
$where[] = " resumo = ? ";
$params[] = $req_resumo;
$n_req++;
}
if (!empty($_POST['status'])) {
$req_status = $_POST['status'];
$where[] = " status = ? ";
$params[] = $req_status;
$n_req++;
}
$sql_where = !empty($where) ? ' where ' . implode(' and ', $where) : '';
echo $sql_where;
$tot = mysqli_prepare($con, "SELECT * FROM solicitacoes $sql_where");
if(!empty($params)) {
//foreach($params as $param) {
// mysqli_stmt_bind_param($tot, "s", $param);
//echo $param;
//}
$params = array_merge(array($tot),
array(str_repeat('s', count($params))),
array_values($params));
print_r($params);
call_user_func_array('mysqli_stmt_bind_param', $params);
// adapated from https://stackoverflow.com/questions/793471/use-one-bind-param-with-variable-number-of-input-vars and http://www.pontikis.net/blog/dynamically-bind_param-array-mysqli may need to be altered
}
echo "SELECT * FROM solicitacoes $sql_where";
mysqli_execute($tot);
If all three values are populated your query should be
SELECT * FROM solicitacoes where usuario = ? and resumo = ? and status = ?
The ? are populated with the values by the driver later in the process. This prevents the user(s) from adding in malicious code to manipulate the SQLs processing.
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28Parameterized_Queries.29
How can I prevent SQL injection in PHP?
I also didn't see where $funcao was set..
You can comment out the mysqli functions and decomment out the echo lines to see what the code does. That is how I confirmed queries were being built as expected.
$predicates = array();
if ($_POST['usuario'] != "") {
$predicates[] = "usuario = '{$_POST["usuario"]}'";
}
if ($_POST['resumo'] != "") {
$predicates[] = "resumo = '{$_POST["resumo"]}'"
}
if ($_POST['status'] != "") {
$predicates[] = "status = '{$_POST["status"]}'"
}
if (count($predicates) == 0) {
// handle case when nothing specified in POST
} else {
$tot = mysqli_query($con, "SELECT * FROM solicitacoes WHERE "
. implode(" and ", $predicates) );
}
I may not have all your logic exactly as required ... but the ideas are there. Use implode() to insert and between the predicates of your WHERE clause (it'll figure out how many are needed, if any). Also, since it is your HTML form that is submitting the POST, you can be certain that at least some value is being passed for each POST variable (so isset() is not required).
The below works as long as the two fields are selected. If neither are selected it works, however my issue is when only one of the fields is selected, it doesn't work. It throws the unbound parameters issue.
I've tried setting a false value of 0 to both of the variables, however that won't work because then the query would be select from where = 0.
Ideas?
public static function searchProfile($status, $fundamt)
{
$database = DatabaseFactory::getFactory()->getConnection();
$sql = "SELECT profile_id, profile_name, profile_url, finance_fundingtype, finance_equitypercent, finance_loanrate, finance_loanlength, finance_fundingamount, info_tradingstatus, info_elevatorpitch, info_patentable, info_industry, info_industry1, info_industry2, info_industry3, info_industry4, seeker_logo_url FROM profile_seeker WHERE profile_status = '1' ";
if ($status) {
$sql .= "AND info_tradingstatus IN (:status) ";
}
if ($fundamt) {
$sql .= "AND finance_fundingamount <= :fundamt ";
}
$query = $database->prepare($sql);
$query->execute(array(':status' => $status, ':fundamt' => $fundamt));
$profiles = array();
$profiles[$profile->profile_id] = new stdClass();
$profiles[$profile->profile_id]->profile_id = $profile->profile_id;
$profiles[$profile->profile_id]->profile_name = $profile->profile_name;
$profiles[$profile->profile_id]->profile_url = $profile->profile_url;
$profiles[$profile->profile_id]->finance_fundingtype = $profile->finance_fundingtype;
$profiles[$profile->profile_id]->finance_equitypercent = $profile->finance_equitypercent;
$profiles[$profile->profile_id]->finance_loanrate = $profile->finance_loanrate;
$profiles[$profile->profile_id]->finance_loanlength = $profile->finance_loanlength;
$profiles[$profile->profile_id]->finance_fundingamount = $profile->finance_fundingamount;
$profiles[$profile->profile_id]->info_tradingstatus = $profile->info_tradingstatus;
$profiles[$profile->profile_id]->info_elevatorpitch = $profile->info_elevatorpitch;
$profiles[$profile->profile_id]->info_patentable = $profile->info_patentable;
$profiles[$profile->profile_id]->info_industry = $profile->info_industry;
$profiles[$profile->profile_id]->info_industry1 = $profile->info_industry1;
$profiles[$profile->profile_id]->info_industry2 = $profile->info_industry2;
$profiles[$profile->profile_id]->info_industry3 = $profile->info_industry3;
$profiles[$profile->profile_id]->info_industry4 = $profile->info_industry4;
$profiles[$profile->profile_id]->seeker_logo_url = $profile->seeker_logo_url;
}
return $profiles;
You could try to check if the variables are set and that they hold a value that is not 0 and this has a string length longer than 0:
if (isset($status) && $status !== 0 && strlen($status) > 0) {
$sql .= "AND info_tradingstatus IN (:status) ";
}
if (isset($fundamt) && $fundamt!== 0 && strlen($fundamt) > 0) {
$sql .= "AND finance_fundingamount <= :fundamt ";
}
You could also try to bind the parameters manually:
$query = $database->prepare($sql);
if (isset($status) && $status !== 0 && strlen($status) > 0) {
$query ->bindParam(':status',$status);
}
if (isset($fundamt) && $status !== 0 && strlen($fundamt) > 0) {
$query ->bindParam(':fundamt',$fundamt);
}
$query->execute();
Your binding error comes because you forgot to use the same if exists statement on your bindings.
Change this...
if ($status) {
$sql .= "AND info_tradingstatus IN (:status) ";
}
if ($fundamt) {
$sql .= "AND finance_fundingamount <= :fundamt ";
}
and
$profiles[$profile->profile_id]->finance_fundingamount = $profile->finance_fundingamount;
$profiles[$profile->profile_id]->info_tradingstatus = $profile->info_tradingstatus;
To this...
if (isset($status) && $status != '') {
$sql .= "AND info_tradingstatus IN (:status) ";
}
if (isste($fundamt) && $fundamt != '') {
$sql .= "AND finance_fundingamount <= :fundamt ";
}
and
if (isset($status) && $status != '') {
$profiles[$profile->profile_id]->finance_fundingamount = $profile->finance_fundingamount;
}
if (isste($fundamt) && $fundamt != '') {
$profiles[$profile->profile_id]->info_tradingstatus = $profile->info_tradingstatus;
}
This will stop the binding if one or both of the text boxes are empty.
I have a site where users can join groups and post topics related to that group, I am having an issue where regardless of the user result, it just shows "member" even on a test account that has no records in the database, can someone please explain what I am doing wrong, thank you.
<?php
$id = $_GET['gid'];
$user = $_SESSION['user_id'];
$iropen = "SELECT * FROM `group_users` WHERE user_id='$user' AND group_id='$id'";
$resultg = mysql_query($iropen);
$rows = mysql_fetch_array($resultg);
if ($rows['accepted'] = 1) {
echo 'member';
} else {
echo 'pending';
}
if ($resultg < 1) {
echo 'join';
}
?>
if ($rows['accepted'] = 1) {
You need two == here.
if ($rows['accepted'] == 1) {
PHP's operator reference, if you need it: http://www.php.net/manual/en/language.operators.php
What #vinodadhikary is saying is that you have single equal-sign instead of the double-equal-sign in your first IF clause. It should be:
if ($rows['accepted'] == 1)...
<?php
$id = $_GET['gid'];
$user = $_SESSION['user_id'];
$iropen = "SELECT * FROM `group_users` WHERE user_id='$user' AND group_id='$id'";
$resultg = mysql_query($iropen);
$rows = mysql_fetch_array($resultg);
$num_results = mysql_num_rows($resultg);
if ($num_results < 1) {
echo "join";
} else if ($rows['accepted'] == 1) {
echo "member";
} else {
echo "pending";
}
?>
Try this
<?php
$id = $_GET['gid'];
$user = $_SESSION['user_id'];
$iropen = "SELECT * FROM `group_users` WHERE user_id='".$user."' AND group_id='".$id."'";
if($resultg = mysql_query($iropen)){
$rows = mysql_fetch_array($resultg)
}
if (mysql_num_rows($resultg) < 1) {
echo 'join';
}else if ($rows['accepted'] == 1) {
echo 'member';
} else {
echo 'pending';
}
?>
I have a script that checks the submitgame table and if both approve1 and approve 2 are not blank it inserts data into clanstats. There is no mysql_error it simply redirects to the header without inserting anything into the clanstats table, so I have no idea what is going on. Below is the code.
<?php
include("user.php");
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM submitgame WHERE id='$id'") or die(mysql_error());
$playerclan = $row['playerclan'];
$opponentclan = $row['opponentclan'];
$win = $row['win'];
$approve1 = $row['approve1'];
$approve2 = $row['approve2'];
if($win == "won") {
$win = 1;
$points = 2;
$win2 = 0;
$points2 = 1;
}
else {
$win = 0;
$points = 1;
$win2 = 1;
$points2 = 2;
}
if($approve1 != "" && $approve2 != "") {
$query=mysql_query("INSERT INTO clanstats (clan, points, wins) VALUES ('$playerclan', '$points', '$win')");
$query=mysql_query("INSERT INTO clanstats (clan, points, wins) VALUES ('$opponentclan', '$points2', '$win2')");
echo mysql_error($query);
}
else {
header("location:../approvegames.php");
}
mysql_close($con);
header("location:../approvegames.php");
?>
<?php
//first off are you connecting, ill presume so
include("user.php");
//sql injection!!!
$id = mysql_real_escape_string($_GET['id']);
$result = mysql_query("SELECT * FROM submitgame WHERE id='$id' limit 1") or die(mysql_error());
//you were missing this
$row=mysql_fetch_array($result);
$playerclan = $row['playerclan'];
$opponentclan = $row['opponentclan'];
$win = $row['win'];
$approve1 = $row['approve1'];
$approve2 = $row['approve2'];
if($win == "won") {
$win = 1;
$points = 2;
$win2 = 0;
$points2 = 1;
}else{
$win = 0;
$points = 1;
$win2 = 1;
$points2 = 2;
}
if($approve1 != "" && $approve2 != "") {
//you can have multiple inserts
$query=mysql_query("INSERT INTO clanstats (clan, points, wins) VALUES
('$playerclan', '$points', '$win'),
('$opponentclan', '$points2', '$win2')");
header("location:../approvegames.php");
//adding die after the header will make sure nothing else gets executed
die();
}else{
header("location:../approvegames.php");
die();
}
//no need to kill the connection as it will close when the script exits
?>
I think you are missing a line. Perhaps something like:
$row = mysql_fetch_row($result)