2013-04-13 5 views
0

지금이 문제를 며칠 동안 해결하려고 노력하고 있으며 벽돌 벽을 치고 있습니다. 내 양식이 문제없이 제출되고 PHP 코드가 오류를 생성하지 않지만 mysql의 테이블을 업데이트하지 않습니다. 어떤 도움이라도 대단히 감사합니다. 많은 코드를 게시하는 것에 대해 미리 사과드립니다. 여기MYSQL 테이블이 업데이트되지 않습니다.

<form style="width:1000px" action="new_recipe.php" method="POST" name="frm_add_recipe"> 

<div id="home_wrapper"> 

<div id="add_recipe_box"> 
<h1>Add a New Recipe</h1> 

<label for="recipe_name">Recipe Name:</label><br/> 
<input type="text" name="recipe_name" class="add_recipe_field"/> 

<label for="ingredient1">Ingredients:</label><br/> 
<input type="text" name="ingredient1" class="add_recipe_field"/> 


<input type="text" name="ingredient2" class="add_recipe_field"/> 


<input type="text" name="ingredient3" class="add_recipe_field"/> 


<input type="text" name="ingredient4" class="add_recipe_field"/> 


<input type="text" name="ingredient5" class="add_recipe_field"/> 


<input type="text" name="ingredient6" class="add_recipe_field"/> 

<label for="ingredient7"></label> 
<input type="text" name="ingredient7" class="add_recipe_field"/> 


<input type="text" name="ingredient8" class="add_recipe_field"/> 


<input type="text" name="ingredient9" class="add_recipe_field"/> 


<input type="text" name="ingredient10" class="add_recipe_field"/><br/> 

<label for="lst_meal">Select meal type:</label> 
<select name="lst_meal" > 
<option value="breakfast">Breakfast</option> 
<option value="lunch">Lunch</option> 
<option value="dinner">Dinner</option> 
</select><br/> 

<label>Recipe Ethnecity:</label> 
<select name="lst_ethnicity"> 
<option value="blank">N/A</option> 
<option value="American">American</option> 
<option value="Asian">Asian</option> 
<option value="Chineese">Chineese</option> 
<option value="German">German</option> 
<option value="Italian">Italian</option> 
<option value="Indian">Indian</option> 
<option value="Mexican">Mexican</option> 
<option value="Thia">Thia</option> 
</select><br/> 


<label for="instructions">Cooking instructions:</label><br/> 

<input name="instructions" type="text" maxlength="250" id="txt_instructions"/> 

<input type="submit" value="Save" /> 

</div> 
</div> 
</form> 

그리고 내 PHP는 다음과 같습니다 :

<?php 
$recipe_name = $_POST['recipe_name']; 
$ingredient1 = $_POST['ingredient1']; 
$ingredient2 = $_POST['ingredient2']; 
$ingredient3 = $_POST['ingredient3']; 
$ingredient4 = $_POST['ingredient4']; 
$ingredient5 = $_POST['ingredient5']; 
$ingredient6 = $_POST['ingredient6']; 
$ingredient7 = $_POST['ingredient7']; 
$ingredient8 = $_POST['ingredient8']; 
$ingredient9 = $_POST['ingredient9']; 
$ingredient10 = $_POST['ingredient10']; 
$lst_meal = $_POST['lst_meal']; 
$lst_ethnicity = $_POST['lst_ethnicity']; 
$instructions = $_POST['instructions']; 

$dbhost = 'localhost' or die("cannot connect"); //Change to webserver info 
$dbname = '*' or die("cannot connect"); //Change to webserver info 
$dbuser = '*' or die("cannot connect"); //Change to webserver info 
$dbpass = '*' or die("cannot connect"); //Change to webserver info 
$conn = mysql_connect($dbhost, $dbuser, $dbpass); 
mysql_select_db($dbname, $conn); 

$recipe_name = mysql_real_escape_string($recipe_name); 
$ingredient1 = mysql_real_escape_string($ingredient1); 
$ingredient2 = mysql_real_escape_string($ingredient2); 
$ingredient3 = mysql_real_escape_string($ingredient3); 
$ingredient4 = mysql_real_escape_string($ingredient4); 
$ingredient5 = mysql_real_escape_string($ingredient5); 
$ingredient6 = mysql_real_escape_string($ingredient6); 
$ingredient7 = mysql_real_escape_string($ingredient7); 
$ingredient8 = mysql_real_escape_string($ingredient8); 
$ingredient9 = mysql_real_escape_string($ingredient9); 
$ingredient10 = mysql_real_escape_string($ingredient10); 
$instructions = mysql_real_escape_string($instructions); 

$query = "INSERT INTO recipes (recipe_name, ingredient1, ingredient2, ingredient3, ingredient4, ingredient5, ingredient6, ingredient7, ingredient8, ingredient9, ingredient10, meal, ethnicity, instructions) 
     VALUES ('' , '$recipe_name' , '$ingredient1' , '$ingredient2' , '$ingredient3' , '$ingredient4' , '$ingredient5' , '$ingredient6' , '$ingredient7' , '$ingredient8' , '$ingredient9' , '$ingredient10' , 'lst_meal' , '$lst_ethnicity' , '$instructions');"; 
mysql_query($query); 
mysql_close(); 
header('Location: home.php'); 
?> 
+4

지옥. PDO를 사용하면 많은 코딩 시간을 절약하고 탈출 할 수 있습니다 ... (그리고 더 쉽게 문제를 해결할 수 있습니다) 쿼리 후 mysql_error();가주는 것은 무엇입니까? – Jon

+1

'VALUES (' ','$ recipe_name '...' – Jon

+0

앞에서' '''를 제거하십시오 mysql_query 다음에 mysql_error()가 삽입 문에 오류가 발생하는지 여부를 확인하기 위해 echo – Amit

답변

3

열 카운트 쿼리에 일치하지 않는이

여기 내 양식 코드입니다. 하나

$query = "INSERT INTO recipes (recipe_name, ingredient1, ingredient2, ingredient3, ingredient4, ingredient5, ingredient6, ingredient7, ingredient8, ingredient9, ingredient10, meal, ethnicity, instructions) 
     VALUES ('$recipe_name' , '$ingredient1' , '$ingredient2' , '$ingredient3' , '$ingredient4' , '$ingredient5' , '$ingredient6' , '$ingredient7' , '$ingredient8' , '$ingredient9' , '$ingredient10' , 'lst_meal' , '$lst_ethnicity' , '$instructions');"; 
+0

고맙다. 내 문제가 해결되었습니다. 그 후에 그것이 작동해야한다. – user2276813

-1

아래

시도 나는 u를 입력 타입 제출에게로 이름을 부여해야한다 생각합니다. 아래처럼 :

<?php 
$save=$_POST['save']; 
?> 

<input type="submit" value="Save" name="save"/> 
+0

. 나에게 알려주세요. 작동하지 않는다면이 문제를 해결하려고 노력할 것입니다. – Rashad

+0

저는 90 %가 틀렸다는 것을 확신합니다. 어디에서 배웠습니까? – asifrc

+0

귀하의 가정이 잘못되었습니다. 이것은 전혀 관련이 없습니다. 따라서 downvote. – bestprogrammerintheworld

0

은 논외에 대한/플래그를 downvote하지 마십시오, 그냥하기 위해 노력하고있어 (그리고이 질문에 표시되는 코드와 직접 거래).

나는이 원치 않는 것을 알고,하지만 난 단지 내가 미래에 귀하의 질문에 하나 같이 반복적 인 상황을 접근 할 때 당신을 도울 것이라고 생각 몇 가지 조언 밖으로 던져 줄 알았는데 :

대신 사용하여 성분 1, 2, 3 .. 당신은 당신의 html에서 입력 배열을 사용할 수 있으며, PHP에서 그것들을 반복합니다. 입력에 대한 name 속성의 숫자를 []으로 바꾸면됩니다. 당신은
<input type="text" name="ingredient[]" class="add_recipe_field"/> 와 성분 입력의 모든 열을 교체하거나 또는 그 대신, 당신은 간단한 PHP 루프를 사용할 수 있습니다

<?php 
for ($i=0; $i < 10; $i++) 
{ 
    echo "<input type='text' name='ingredient[]' class='add_recipe_field'/>"; 
} 
?> 

이것은 당신의 PHP에 배열로 $_POST['ingredient'] 사용할 수있게됩니다. 필자는 PHP 코드 (예, 모든 것)를 다시 작성하여 루프를 반복하는 방법을 설명했습니다 (추가적으로 myqsqli를 사용했습니다). 이 방법을 사용하면 위의 카운터와 mysql 테이블을 변경하여 재료 수를 변경할 수 있습니다 (아래 코드를 수정할 필요가 없습니다). 또한, (나 자신을 할 것이라고) 당신은 몇 가지 자바 스크립트 (또는 jquery, 등)와 함께 시작하는 하나의 입력을 작성하고 자동으로 사용자가 재료에 입력 할 때마다 입력을 추가 .. 그냥 생각. 그러나 참으로, 이것이 도움이되는지 그리고 그것이 모두 의미가 있는지 알게하십시오. 그리고 물론, 나는 완벽하고 효율적인 코드의 모범이 결코 아니므로,이 답변을 읽는 것을 괴롭힌 누군가가 내가 작성한 것을 향상시키는 방법에 대해 의견을 말하고 싶다면 꼭 읽어보십시오.

<?php 
$dbhost = 'localhost'; //Change to webserver info 
$dbname = '*'; //Change to webserver info 
$dbuser = '*'; //Change to webserver info 
$dbpass = '*'; //Change to webserver info 

//Connect to database 
$mysqli = mysqli($dbhost, $dbuser, $dbpass, $dbname); 
//Check for successful connection 
if ($mysqli->connect_errno) { 
    die("Failed to connect to MySQL: ".$mysqli->connect_error); 
} 

//Mysql table fields (besides ingredients) 
$sqla = "`recipe_name`, `meal`, `ethnicity`, `instructions`"; 

//Manually add corresponding values (could also be done in a loop) 
$sqlb = $_POST['recipe_name']; //You Probably want some sort of validation here 
$sqlb .= ", ".$_POST['lst_meal']; 
$sqlb .= ", ".$_POST['lst_ethnicity']; 
$sqlb .= ", ".$_POST['instructions']; 

//Loop through ingredients and add to query 
$comma = ", "; //Leave empty if all mysql fields within loop 
$ingredients = $_POST['ingredient']; 
foreach(array_keys($ingredients) as $k) 
{ 
    if ($ingredients[$k]!="") //If not blank 
    { 
     //Add mysql field name (+1 since index starts at 0) 
     $sqla .= $comma."`ingredient".($k+1)."`"; 
     //Add value to other half of string 
     $sqlb .= $comma."\"".$mysqli->real_escape_string($ingredients[$k])."\""; 
     $comma = ", "; //Insert comma in subsequent iterations 
    } 
} 
//Put the query together 
$query = "INSERT INTO `recipes` (".$sqla.") VALUES (".$sqlb.");"; 

//Try the query and die the error + sql on error 
if (!$mysqli->query($query)) 
{ 
    die("MySQL Error: ".$mysqli->error."<br>Query: ".$query); 
} 
header('Location: home.php'); 
?> 
+0

PDO를 사용하십시오. MySQLi는 불완전하고'real_escape_string' _이 충분히 효과적 일 수 있지만 라이브러리 자체는 부족하고 준비된 쿼리를 사용하는 것이 주입 공격을 막는 더 좋은 방법입니다. – Jon

+0

@ 존 나는 PDO를 한 번도 사용 해본 적이 없으며, 단지 * 그것에 관해서 만 알고있다. (물론 나 자신을 위해 진짜로 real_esc를 사용하지는 않을 것이다.) 당신은 MySQLi가 불완전한/PDO가 더 좋은 방법의 예가 있나? – asifrc

+1

준비된 명령문을 사용해 본 적이 있다면, 불완전한 이유를 이해할 수 있습니다. 예를 들어 결과를 바인드하거나 [mysqli_stmt :: get_result()'] (http : //)를 사용해야합니다. us2.php.net/manual/en/mysqli-stmt.get-result.php). 예상대로 유행의 결과로 작업하십시오. 오직'get_result()'함수는 신뢰할 수 없으며 컴파일 된 모든 버전에서 작동하지 않으므로 의존 할 수 없습니다 - 이식성있는 코드를 가지고 있다는 것을 의미하므로 최소한의 말로 지루한 각각의 예상 된 결과를 바인드해야합니다 . – Jon

관련 문제