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;
}
}
}
Related
Please I've been trying to create a function that would query a DB, select from the table, and if the row count is not equal to 6, then a row from the table and repeat (or maybe duplicate) until the row count is equal to 6. I've search for this here in StackOverflow, but didn't get anything close. Please if you have a similar link to this, please post it here, and I'll give it a go.
Here's my code:
//List All active adverts
function showActiveAdverts()
{
$status = 1;
//Build final queries.
$query = mysql_query("SELECT * FROM table WHERE
status = '".mysql_real_escape_string($status)."' ORDER BY rand() LIMIT 6") or die(mysql_error());
$count = mysql_num_rows($query);
$row = mysql_fetch_assoc($query);
# My question here, check if the $count >= 1 && $count != 6, then do getDefaultBannner() and repeat it until it runs for 6 times.
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
Here's the code for getDefaultBannner()
function getDefaultBannner()
{
$status = 6;
$query = mysql_query("SELECT id FROM table WHERE status = '".mysql_real_escape_string($status)."' ")
or die(mysql_error());
$count = mysql_num_rows($query);
$row = mysql_fetch_assoc($query);
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
Thanks in advance!
You can rewrite your code as this
//List All active adverts
$query = mysql_query("SELECT * FROM table WHERE
status = '".mysql_real_escape_string($status)."' ORDER BY rand() LIMIT 6") or die(mysql_error());
$count = mysql_num_rows($query);
if($count >= 1 && $count != 6)
$list = getDefaultBannner();
else
$list = showActiveAdverts($query);
function showActiveAdverts($query)
{
$status = 1;
//Build final queries.
$row = mysql_fetch_assoc($query);
if($count >= 1){
do{
$list[] = $row['id'];
}while($row = mysql_fetch_assoc($query));
return $list;
}
else{ return FALSE; }
}
So I've got a dropdown that has a list of customers that you can select from. It uses a function (that someone else built) which works fine when there are 2 or more customers but dies when there it only one. When there's one customer, each item in the dropdown is the first character of each column for that one customer.
Here is the function:
function getCustomerBy($column = "",$value = "")
{
global $conn;
if ($value == '')
{
return(null);
}
$sel = "SELECT
customers.*,
customerStatus.code customerStatus
FROM customers,
customerStatus
WHERE customer_id
and customerStatus.id = customers.customerStatus_id and ". mysqli_real_escape_string($conn,$column) ."='". mysqli_real_escape_string($conn,$value) ."'";
// error_log($sel);
$run = mysqli_query($conn, $sel);
$check = mysqli_num_rows($run);
if ($check ==1)
{
$row = mysqli_fetch_assoc($run);
return($row);
}
elseif($check >1)
{
$rows = array();
while ($row = mysqli_fetch_assoc($run))
{
$rows[] = $row;
}
return($rows);
}
else
{
return(null);
}
}
I'm fairly certain that it's the ($check == 1) stuff but I can't work out the best way to re-do all of that to make it work without causing other errors (specifically "cannot modify header")
This is what's called up on the page with the dropdown:
$customers = getCustomerBy('users_user_id',$user['user_id']);
Also, here is the code for the dropdown:
<?
foreach ($customers as $customer)
{
$selected = '';
if (isset($gig['customers_customer_id']) && $customer['customer_id'] == $gig['customers_customer_id'])
{
$selected = ' selected ';
}
echo "\t<option value=\"".$customer['customer_id']."\" $selected>".$customer['customer_company_name']."</option>";
}
?>
The code that builds the dropdown is expecting an array of arrays, but instead when it's a single row you're passing it an array of strings. Treat both cases ($check > 0) the same.
function getCustomerBy($column = "",$value = "")
{
global $conn;
if ($value == '')
{
return(null);
}
$sel = "SELECT
customers.*,
customerStatus.code customerStatus
FROM customers,
customerStatus
WHERE customer_id
and customerStatus.id = customers.customerStatus_id and ". mysqli_real_escape_string($conn,$column) ."='". mysqli_real_escape_string($conn,$value) ."'";
// error_log($sel);
$run = mysqli_query($conn, $sel);
$check = mysqli_num_rows($run);
if($check > 0)
{
$rows = array();
while ($row = mysqli_fetch_assoc($run))
{
$rows[] = $row;
}
return($rows);
}
else
{
return(null);
}
}
I assume there's copy/paste errors in your query because it doesn't look right.
I don't know how the returning array is used by the rest of your code but you can try the following:
Change:
if ($check ==1) {
$row = mysqli_fetch_assoc($run);
return($row);
}
To this:
if ($check == 1) {
$rows = array();
$rows[] = mysqli_fetch_assoc($run);
return($rows);
}
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."%";
?>
I have a BOOLEAN in my table, set to 0 or 1.
$test = mysql_query("SELECT status FROM mydb WHERE email = 'admin#mail.com'") or die(mysql_error());
if ($test == 0) {
echo "FF";
} elseif ($test == 1) {
echo "ON";
}
But this doesn't work, why? I tried true and false, that doesn´t work either.
You are not actually fetching the result.
$test = mysql_query("SELECT status FROM mydb WHERE email = 'admin#mail.com'");
if (!$test) {
die(mysql_error());
} else {
$res = $test;
}
$row = mysql_fetch_assoc($res);
var_dump($row);
$test is just the results from the query. You want to see if you get a row try this:
$result = mysql_query("SELECT status FROM mydb WHERE email = 'admin#mail.com'")or die(mysql_error());
$row_count = mysql_num_rows($result);
if($row_count == 0)
{
echo "FF";
}
else if($row_count == 1)
{
echo "ON";
}
If you need to know the value of status
$result = mysql_query("SELECT status FROM mydb WHERE email = 'admin#mail.com'")or die(mysql_error());
while($data = mysql_fetch_assoc($result))
{
if($data['status'] == 0)
{
echo "FF";
}
else if($data['status'] == 1)
{
echo "ON";
}
}
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)