2016-04-25 3 views
-1

Я хочу передать переменную на следующую страницу, но я, похоже, не работает должным образом. Я сделал что-то на другой странице, но теперь он не работает.PHP Передать переменную на следующую страницу не работает

Это Metod им с помощью передать переменные (email.php): <div class='alternativ'> <td width="50%" style=" padding:5px;"> <form method='GET' action='excelimport.php'> <input type='hidden' name='pidnew3' value='$pidnew2'> <input type="submit" name="submit"> </form></td> </div>

и excelimport.php у меня есть это: $pidnew4 = $_POST['pidnew3'];


Im получаю 2 ошибки в excelimport. PHP:

Notice: Undefined index: pidnew3 in D:\home\site\wwwroot\devlopment\excelimport.php on line 77 

его ВЕ следующим образом: $pidnew4 = $_POST['pidnew3'];


Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in D:\home\site\wwwroot\devlopment\excelimport.php on line 102 

и это ВЕ к этому: $recResult = mysql_fetch_array($sql);


У меня есть этот PHP (email.php) страницы, который я хочу, чтобы перейти к другой .:

<?php 
include_once 'includes/db_connect.php'; 
include_once 'includes/functions2.php'; 
include_once 'includes/config.php'; 
error_reporting(-1); ini_set('display_errors', 1); 

//Start av sessions 
sec_session_start(); 
if (login_check($mysqli) == true) { 
    $logged = 'Inloggad'; 
} else { 
    $logged = 'utloggad'; 
} 


$uploadedStatus = 0; 

if (isset($_POST["submit"])) { 
if (isset($_FILES["file"])) { 
//if there was an error uploading the file 
if ($_FILES["file"]["error"] > 0) { 
echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; 
} 
else { 
if (file_exists($_FILES["file"]["name"])) { 
unlink($_FILES["file"]["name"]); 
} 
$storagename = "discussdesk.xlsx"; 
move_uploaded_file($_FILES["file"]["tmp_name"], $storagename); 
$uploadedStatus = 1; 
} 
} else { 
echo "Ingen fil vald <br />"; 
} 
} 

?> 


<!DOCTYPE html> 
<html> 
<head> 
    <title>Kandidater</title> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=0.709"> 
    <!-- Latest compiled and minified CSS --> 
    <link rel="stylesheet" href="css/bootstrap.min.css"> 
    <!-- jQuery library --> 
    <script src="js/jquery.min.js"></script> 
    <!-- Latest compiled JavaScript --> 
    <script src="js/bootstrap.min.js"></script> 
    <link rel="stylesheet" type="text/css" href="main.css"> 
    <link rel="shortcut icon" href="logo/wfmini.png"> 

    <script type="text/javascript" language="javascript"> 
    function checkedbox(element) { 
     var checkboxes = document.getElementsByTagName('input'); 
     if (element.checked) { 
      for (var i = 0; i < checkboxes.length; i++) { 
       if (checkboxes[i].type == 'checkbox') { 
        checkboxes[i].checked = true; 
       } 
      } 
     } else { 
      for (var i = 0; i < checkboxes.length; i++) { 
       console.log(i) 
       if (checkboxes[i].type == 'checkbox') { 
        checkboxes[i].checked = false; 
       } 
      } 
     } 
    } 
    </script> 
<script src="js/tinymce/js/tinymce/tinymce.min.js"></script> 
<script>tinymce.init({selector:'textarea'});</script> 
</head> 

<body class="dashboardadmin"> 

<ss="container-fluid" style="width:50%;"> 
    <br> 
    <center><h3>Skicka email till kandidater</h3></center> 

    <br> 
    <p>Välj kandidater</p> 

    <form method="post" action=""> 
    <?php 

    $pidnew2 = $_GET['pidnew']; 

    // Retrieve Email from Database 
    $getemail = mysql_query("SELECT * FROM Email_Users WHERE pid='".$pidnew2."'"); 

    if (!$getemail) die('MySQL Error: ' . mysql_error()); 

    echo '<table class="table table-bordered">'; 
    echo "<thead> 
      <tr> 
      <th><input type='checkbox' onchange='checkedbox(this)' name='chk'/></th> 
      <th>Förnamn</th> 
      <th>Efternamn</th> 
      <th>Email</th> 
      </tr> 
      </thead>"; 

    if (mysql_num_rows($getemail) == 0) {  
    echo "<tbody><tr><td colspan='3'>No Data Avaialble</td></tr></tbody>";  
    } 

    while ($row = mysql_fetch_assoc($getemail)) {  
     echo "<tbody><tr><td><input value='".$row['Email']."' type='checkbox' name='check[]'/></td>"; 
     echo "<td >".$row['fornamn']."</td>"; 
     echo "<td >".$row['efternamn']."</td>"; 
     echo "<td >".$row['Email']."</td></tr></tbody>"; 
    } 
    echo "</table>"; 
    ?> 
    </form> 
    </center> 
    <br> 
</div> 


<table width="600" style="margin:115px auto; background:#f8f8f8; border:1px solid #eee; padding:10px;"> 

<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data"> 





<tr><td colspan="2" style="font:bold 15px arial; text-align:center; padding:0 0 5px 0;">Ladda upp kandidater</td></tr> 

<tr> 

<td width="50%" style="font:bold 12px tahoma, arial, sans-serif; text-align:right; border-bottom:1px solid #eee; padding:5px 10px 5px 0px; border-right:1px solid #eee;">Välj fil</td> 

<td width="50%" style="border-bottom:1px solid #eee; padding:5px;"><input type="file" name="file" id="file" /></td> 

</tr> 





<tr> 

<td style="font:bold 12px tahoma, arial, sans-serif; text-align:right; padding:5px 10px 5px 0px; border-right:1px solid #eee;">Send</td> 

<div class='alternativ'> 
<td width="50%" style=" padding:5px;"> 
<form method='GET' action='excelimport.php'> 
    <input type='hidden' name='pidnew3' value='$pidnew2'> 
    <input type="submit" name="submit"> 
</form></td> 
</div> 

</tr> 

</table> 

<?php if($uploadedStatus==1){ 

header('Location: excelimport.php'); 

}?> 





</form> 

<script type="text/javascript"> 

    var _gaq = _gaq || []; 
    _gaq.push(['_setAccount', 'UA-38304687-1']); 
    _gaq.push(['_trackPageview']); 

    (function() { 
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; 
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; 
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); 
    })(); 

</script> 


</body> 
</html> 

И вот другой (excelimport.php):

<?php 
include_once 'includes/db_connect.php'; 
include_once 'includes/functions2.php'; 
include_once 'includes/config.php'; 
error_reporting(-1); ini_set('display_errors', 1); 

//Start av sessions 
sec_session_start(); 
if (login_check($mysqli) == true) { 
    $logged = 'Inloggad'; 
} else { 
    $logged = 'utloggad'; 
} 

?> 

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<link rel="stylesheet" type="text/css" href="main.css"> 
<link rel="shortcut icon" href="logo/wfmini.png"> 
</head> 
<body class="dashboardadmin"> 
<div class="innehall"> 


    </div> 


<p> 




<?php 



set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/'); 
include 'PHPExcel/IOFactory.php'; 

$pidnew4 = $_POST['pidnew3']; 



$inputFileName = 'discussdesk.xlsx'; 

try { 
    $objPHPExcel = PHPExcel_IOFactory::load($inputFileName); 
} catch(Exception $e) { 
    die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage()); 
} 


$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true); 
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet 


for($i=2;$i<=$arrayCount;$i++){ 
$userfName = trim($allDataInSheet[$i]["A"]); 
$usereName = trim($allDataInSheet[$i]["B"]); 
$userMobile = trim($allDataInSheet[$i]["C"]); 


$query = "SELECT name FROM Email_Users WHERE fornamn = '".$userfName."' and efternamn '".$usereName."' and email = '".$userMobile."' and pid = '".$pidnew4."'"; 
$sql = mysql_query($query); 
$recResult = mysql_fetch_array($sql); 
$existName = $recResult["fornamn"]; 
if($existName=="") { 
$insertTable= mysql_query("insert into Email_Users (fornamn, efternamn, email, pid) values('".$userfName."', '".$usereName."', '".$userMobile."', '".$pidnew4."');"); 


$msg = 'Record has been added. <div style="Padding:20px 0 0 0;"><a href="">Go Back to tutorial</a></div>'; 
} else { 
$msg = 'Record already exist. <div style="Padding:20px 0 0 0;"><a href="">Go Back to tutorial</a></div>'; 
} 
} 
echo "<div style='font: bold 18px arial,verdana;padding: 45px 0 0 500px;'>".$msg."</div>"; 

?> 


</body> 

</html> 
+0

Это Metod им с помощью передать переменные '

' – Fredrik

+0

и вторая страница '$ pidnew4 = $ _POST ['pidnew3']; ' – Fredrik

+0

Пожалуйста, обновите свой вопрос с содержанием комментариев и сообщите нам, в чем проблема. Прямо сейчас нет вопроса. «Не работает» не полезно. Сообщения об ошибках PHP? Ошибки консоли? – mplungjan

ответ

-2

Вы должны изменить метод в форме POST, поскольку вы пытаетесь получить переменную, прошедшую через 'GET'. Или, как показано ниже, вы можете получить переменную с помощью метода «GET».

$pidnew4 = $_GET['pidnew3']; 
+0

@Fredrik Откуда возникает $ _GET ['pidnew'], он, кажется, содержит значение pidnew3. Если он пуст, это объясняет, почему ваш индекс pidnew3 не будет определен, поскольку значение не будет отправлено через форму. – IamNguele

+0

Я действительно не знаю, что я сделал неправильно. Потому что я использую некоторые принцессы на других страницах без большой проблемы. Я думаю, что что-то в моем коде, которое перераспределило страницы, а затем теряет «pidnew», возможно? – Fredrik

0
<form method='GET' action='excelimport.php'> 
    <input type='hidden' name='pidnew3' value='$pidnew2'> 
    <input type="submit" name="submit"> 
</form> 

В этой форме вы упомянули метод GET и вы передаете переменную с помощью метода GET в вашей другой странице.

Вы не можете получить переменную pidnew3 на другую страницу, потому что используете метод POST для получения переменной pidnew3.

Вам просто нужно изменить строку ниже от

$pidnew4 = $_POST['pidnew3']; 

в

$pidnew4 = $_GET['pidnew3']; 
+0

Спасибо за повтор, но эта работа с дозатором. Я действительно не знаю, что я сделал неправильно. Потому что я использую некоторые принцессы на других страницах без большой проблемы. Я думаю, что что-то в моем коде, которое перераспределило страницы, а затем теряет «pidnew», возможно? – Fredrik

0

Я просто понял, что может быть не так, вы не отображать значение $ pidnew2 здесь

<form method='GET' action='excelimport.php'> 
    <input type='hidden' name='pidnew3' value='$pidnew2'> 
    <input type="submit" name="submit"> 
</form> 

Вы должны заменить этот блок на

<form method='GET' action='excelimport.php'> 
    <input type='hidden' name='pidnew3' value='<?php echo $pidnew2; ?>'> 
    <input type="submit" name="submit"> 
</form> 

Тогда вы получите значение переменной $ pidnew2, а не строку «$ pidnew2»

Смежные вопросы