I have a form that has a variable number of input fields, and i now try to get these values in my database. I got this code from another question here and all the replies where implying that they got it working..so i think i'm doing something wrong here.
I get no error, it just enters one empty entry/row in my database every time i submit the form. The $_POST array is filled with all the data i need, it shows when i print_r it.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (
!empty($_POST['homeTeam']) && !empty($_POST['awayTeam']) && !empty($_POST['homeWin']) && !empty($_POST['awayWin']) &&
is_array($_POST['homeTeam']) && is_array($_POST['awayTeam']) && is_array($_POST['homeWin']) && is_array($_POST['awayWin']) &&
count($_POST['homeWin']) === count($_POST['awayWin'])
) {
$homeTeam_array = $_POST['homeTeam'];
$awayTeam_array = $_POST['awayTeam'];
$homeWin_array = $_POST['homeWin'];
$awayWin_array = $_POST['awayWin'];
for ($i = 0; $i < count($homeTeam_array); $i++) {
$homeTeam = mysql_real_escape_string($homeTeam_array[$i]);
$awayTeam = mysql_real_escape_string($awayTeam_array[$i]);
$homeWin = mysql_real_escape_string($homeWin_array[$i]);
$awayWin = mysql_real_escape_string($awayWin_array[$i]);
$sql = "INSERT IGNORE INTO CalcOdds (homeTeam, awayTeam, homeWin, awayWin) VALUES ('$homeTeam', '$awayTeam', '$homeWin', '$awayWin')";
$conn->query($sql);
$conn->close();
}
}
echo "<pre>";
print_r($_POST);
echo "</pre>";
echo 'Done!';
}
?>
I think the problem is because you have $conn->close(); inside the for loop try to add it after the loop like this:
for ($i = 0; $i < count($homeTeam_array); $i++) {
$homeTeam = mysql_real_escape_string($homeTeam_array[$i]);
$awayTeam = mysql_real_escape_string($awayTeam_array[$i]);
$homeWin = mysql_real_escape_string($homeWin_array[$i]);
$awayWin = mysql_real_escape_string($awayWin_array[$i]);
$sql = "INSERT IGNORE INTO CalcOdds (homeTeam, awayTeam, homeWin, awayWin) VALUES ('$homeTeam', '$awayTeam', '$homeWin', '$awayWin')";
$conn->query($sql);
}
$conn->close();
Instead of doing !empty() I'd do isset()
By the looks of things you haven't actually established a connection to your database.
Make sure that the data actually gets through the if() statement by using a echo() for example.
Related
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.
I have a problem with comparing 2 values and let 1 value change within the if statement. But ofcourse when I reload the page it picks up the first value again. I'm using this code to set some information in a database when a machine is turned on or off.
$urlMachineON = 'http://192.168.0.150/awp/Shredder/PLCfiles/IOmachineActive.html';
// get content
$contentMachineON = file_get_contents($urlMachineON);
//remove first 2 characters
$truncate = substr($contentMachineON, 2);
//remove last 5 characters
$MachineOn = substr($truncate, 0, -5);
//MachineON can only be 1 or 0
$currentState = 2;
if ($MachineOn != $currentState)
{
$stmt = $conn->prepare("INSERT INTO machineactiviteit (Time, MachineStatus) VALUES(NOW(), ?)");
$stmt->bind_param('s', $MachineOn);
if ($stmt->execute() === TRUE)
{
$currentState = $MachineOn;
echo 'success';
}
else
{
echo $conn->error;
}
$stmt->close();
}
elseif($MachineOn == $currentState)
{
echo 'do nothing';
}
So when I do this he will always use the if statement since the $currentState and $MachineOn are always different from each other. In C# you have something like initalize component to set the value one time to a specific value. But I haven't found anything about that in php. So my question is can I set a value only once? Or should I solve this another way?
This is how it should work:
first attempt before: currentState = 2; MachineOn = 0; after: currentState= 0; MachineOn = 0;
second attempt before: currentState= 0; MachineOn = 0; after: currentState= 0; MachineOn = 0;
third attempt before: currentState= 0; MachineOn = 1; after: currentState= 1; MachineOn = 1; (I can change the MachineOn value with a button).
Just save $currentState value somewhere. For example in file or in database.
$currentState = file_get_contents('filepath'); // last saved state (check if is set!)
if($currentState !== $MachineOn) {
file_put_contents('filepath', $MachineOn); // Save current state
} else {
file_put_contents('filepath', 2); // Save other state
}
This is pseoudocode. Remember to check if file exist and has value.
So I have a query that I am returning all of the items into a mysql_fetch_array. Now, I know I could write another query and just select the items I need into a seperate query but, is there a way to just filter from the larger query what I want dependent on $_GET?
So, in english the user comes from a hyperlink that has ?id=1 and I peform a while that gets the all the values but, only display the $_GET['id'] items in a list
<?php //give ma all values but only echo out list of the $_GET['id'] in the url
while ($row = mysql_fetch_array($result) {
$id = $rowvideo["id"];
$title = $rowvideo["title"];
$length = $rowvideo["length"];
}
echo("<li><a href='#'>". $title." " .$length. "</a></li>");
?>
Hope this makes sense. Thank you all.
If you do not want a second query to get just what you need, a simple-if-statement in your loop should work:
<?php
$getId = isset($_GET['id']) ? $_GET['id'] : false;
//give ma all values but only echo out list of the $_GET['id'] in the url
while ($row = mysql_fetch_array($result)) {
$id = $row["id"];
$title = $row["title"];
$length = $row["length"];
if ($id == $getId) {
echo("<li><a href='#'>". $title." " .$length. "</a></li>");
}
}
?>
Note that I declared $getId outside of the loop to prevent having to use isset() during every iteration. If you don't verify if it's set and attempt to use it it will throw an undefined index warning - assuming you have error_reporting turned on (with that level enabled).
Alternatively, you could use PHP's array_filter() on the data after you've parsed it all:
$results = array();
while ($row = mysql_fetch_array($result)) $results[] = $row;
if (isset($_GET['id'])) {
$filtered = array_filter($results, function($element) use ($_GET['id']) { return ($element['id'] == $_GET['id']); });
$results = $filtered;
}
foreach ($results as $result) {
echo("<li><a href='#'>". $result['title']." " .$result['length']. "</a></li>");
}
My personal opinion would be to be more efficient and write the second query though, assuming of course you don't actually need all of the results when an id is specified. It would be as simple as:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$query = 'SELECT id, title, length FROM table WHERE id=' . (int)$_GET['id'];
} else {
$query = 'SELECT id, title, length FROM table';
}
// your existing code as-is
A little more clarity here:
This will allow the filter by id in the url by specifying id=xxx, IF xxx is an integer that is positive. So id of 'bob' or -1 will not filter the results still giving all results
$filter=false;
if(isset($_GET['id']))
{
$filter_id=intval($_GET['id']);
if($id>0) $filter=true;
}
while($row = mysql_fetch_array($result))
{
if( (!$filter) || ( ($filter) && ($filter_id==$row['id']) ) )
{
$id = $row["id"];
$title = $row["title"];
$length = $row["length"];
// do other stuff here
}
}
I also changed $rowvideo to $row as this is the array you used to fetch the results.
<?php //give ma all values but only echo out list of the $_GET['id'] in the url
while ($row = mysql_fetch_array($result)) {
$id = $rowvideo["id"];
$title = $rowvideo["title"];
$length = $rowvideo["length"];
if ($id == $_GET['id']) { // or even ===
echo("<li><a href='#'>". $title." " .$length. "</a></li>");
}
}
?>
I am trying to create logic to see what checkbox is selected (of 5 possible checkboxes) and if it is selected assign it a value of 0. if it is not selected I was to assign it a value of 1. The proceeding code snippet highlight this but throws a parse error in my else statement and I cannot fighure out why.
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = 'unchecked';
$chkBox2 = 'unchecked';
$chkBox3 = 'unchecked';
$chkBox4 = 'unchecked';
$chkBox5 = 'unchecked';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
else{
$chkBox1 = '1';
}
}//End of chkBox1Selected logic
You don't understand how checkboxes work. If a checkbox is deselected before posting, it will not be set on post.
Therefore, the only condition that will ever be present in your code is that every value will show as 1, since they cannot be overridden.
Take this snippet and try it out. It dynamically loops for the amount of variables you need and assigns the values based upon the submitted value.
$_POST['chkBox4'] = 'test';
for( $i = 1; $i <= 5; $i++ )
{
$name = 'chkBox' . $i;
$$name = !isset( $_POST[$name] ) ? 0 : $_POST[$name];
}
print $chkBox2 . ' // '. $chkBox4;
http://codepad.org/51RotnCf
Ok I got it to work from a syntax standpoint, however now no matter what is selected it is still assigning a value of 1 to all the checkboxes and not changing the selected checkbox to a value of 0. Here is the new code that is correct from a syntax standpoint but defaults to 1 no matter what:
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = '1';
$chkBox2 = '1';
$chkBox3 = '1';
$chkBox4 = '1';
$chkBox5 = '1';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
}//End of chkBox1Selected logic
if (isset($_POST['chkBox2'])) {
if ($chkBox2 == 'chkBox2Selected') {
$chkBox2 = '0';
}
}//End of chkBox2Selected logic
if (isset($_POST['chkBox3'])) {
if ($chkBox3 == 'chkBox3Selected') {
$chkBox3 = '0';
}
}//End of chkBox3Selected logic
if (isset($_POST['chkBox4'])) {
if ($chkBox4 == 'chkBox4Selected') {
$chkBox4 = '0';
}
}//End of chkBox4Selected logic
if (isset($_POST['chkBox5'])) {
if ($chkBox5 == 'chkBox5Selected') {
$chkBox5 = '0';
}
}//End of chkBox5Selected logic
Like the title says, PHP is really confusing me on a simple if comparison statement that's returning the opposite of what it should be returning. I'm trying to compare 2 datetime's that are first converted to strings:
//Fetched db query, this returns 2012-06-23 16:00:00
$databaseDateTime = strtotime($row['time']);
//This now returns 1340481600
//today's date and time I'm comparing to, this returns 2012-06-22 17:14:46
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
//this now returns 1340399686
Great, everything works perfect so far. Now here's where things get hairy:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
And this returns 'past', which of course it shouldn't. Please tell me I'm missing something. My project kind of depends on this functionality being airtight.
**EDIT***
Thanks guys for taking the time to help me out. Let me post the entire code because a few of you need more context. The request is coming from an IOS5 to my backend code and json is being sent back to the phone.
<?php
//all included files including $link to mysqli_db and function sendResponse()
function getEvents($eventType, $eventArray) {
global $link;
global $result;
global $i;
global $todaysDateTime;
foreach ($eventArray as $key => $value) {
$sqlGetDeal = mysqli_query($link, "SELECT time FROM deals WHERE id='$value' AND active='y' LIMIT 1") or die ("Sorry there has been an error!");
while ($row = mysqli_fetch_array($sqlGetDeal)) {
//compare times to check if event already happened
$databaseDateTime = strtotime($row['time']);
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
$result[$i] = array(
'whenDeal' => $eventType,
'time' => $databaseDateTime,
);
$i++;
}//end while
}//end foreach
}
if (isset($_GET['my'])) {
//$_GET['my'] comes in as a string of numbers separated by commas e.g. 3,2,6,3
$myDeals = preg_replace('#[^0-9,]#', '', $_GET['my']);
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
$result = array();
$kaboomMy = explode(",", $myDeals);
$i = 1;
if ($myEvents != "") {
getEvents('future', $kaboomMy);
}//end if
sendResponse(200, json_encode($result));
} else {
sendResponse(400, 'Invalid request');
} //end $_POST isset
?>
Found a quick hack around the issue. I just added a local variable to my function and rearranged my compare statement
//added local variable $eventTyppe to function
$eventTyppe;
changed compare from:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
to:
if ($todaysDateTime < $databaseDateTime ) {
$eventTyppe = $eventType;
} else {
$eventTyppe = 'past';
}
Notice if I rearrange compare:
if ($databaseDateTime < $todaysDateTime ) {
$eventTyppe = 'past';
} else {
$eventTyppe = $eventType;
}
I still get the same error. This is the weirdest thing I've ever seen and the first PHP bug I've run into (I'm assuming it's a PHP bug).
Could you print the values of the times right before this line?
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
Since that one is declared as global I'm wondering if is it coming back incorrectly.