【问题标题】:Query in php fails with get and spacesphp中的查询因get和空格而失败
【发布时间】:2013-12-19 20:26:37
【问题描述】:

希望有人可以提供帮助。在我添加一个带有空格的新项目之前,我的动态下拉菜单一直运行良好。这让我很困惑,因为我的第二个下拉列表中有带空格的项目,并且查询运行良好,但第一个下拉列表失败。我试图找到任何会导致失败的差异,但我就是看不到它。这是我发现的脚本的混合体,我对 Javascript 和 PHP 真的很陌生,所以我迷路了。我希望有人能指出我的错误。这是我认为您需要查看的代码第一个脚本是控制失败的下拉列表的脚本,第二个脚本正在运行:

    <script type="text/javascript">
function AjaxFunction()
{

var ddstring = document.getElementById("name");
var ddindex = ddstring.options[ddstring.selectedIndex].value;

if (ddindex != 0){  
var httpxml;
try
  {
  // Firefox, Opera 8.0+, Safari
  httpxml=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
          try
                    {
                 httpxml=new ActiveXObject("Msxml2.XMLHTTP");
                    }
            catch (e)
                    {
                try
            {
            httpxml=new ActiveXObject("Microsoft.XMLHTTP");
             }
                catch (e)
            {
            alert("Your browser does not support AJAX!");
            return false;
            }
            }
  }
function stateck() 
    {
    if(httpxml.readyState==4)
      {
//alert(httpxml.responseText);
var myarray = JSON.parse(httpxml.responseText);
var myarray=myarray.split(",");
for(j=document.searchform.type.options.length-1;j>=0;j--)
{
document.searchform.type.remove(j);
}
for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");

optn.text = myarray[i];
optn.value = myarray[i];
document.searchform.type.options.add(optn);
} 
{
var optn2 = document.createElement("OPTION");

optn2.text = "Select Type";
optn2.value = '%';
document.searchform.type.options.add(optn2,0);
} 
{
document.searchform.type.disabled=false;
document.searchform.type.selectedIndex = 0;
var defaultdd = "<?php echo $_SESSION['type'] ?>";

if (defaultdd != ""){
document.getElementById('s2').value = defaultdd;
if (defaultdd != "%"){
AjaxFunction2(); 
}

}
}

  }
}
var url="dd.php";
var cat_id=document.getElementById('name').value;
url=url+"?cat_id="+cat_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(url);
httpxml.open("GET",url,true);
httpxml.send(null);
}

else {
    document.searchform.type.selectedIndex = 0;
    document.searchform.subcat.selectedIndex = 0;
    document.searchform.type.disabled=true;
    document.searchform.subcat.disabled=true;       
}
}
</script>




<script type="text/javascript">
function AjaxFunction2()
{
var httpxml;
try
  {
  // Firefox, Opera 8.0+, Safari
  httpxml=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
          try
                    {
                 httpxml=new ActiveXObject("Msxml2.XMLHTTP");
                    }
            catch (e)
                    {
                try
            {
            httpxml=new ActiveXObject("Microsoft.XMLHTTP");
             }
                catch (e)
            {
            alert("Your browser does not support AJAX!");
            return false;
            }
            }
  }
function stateck() 
    {
    if(httpxml.readyState==4)
      {
//alert(httpxml.responseText);
var myarray = JSON.parse(httpxml.responseText);
var myarray=myarray.split(",");
for(j=document.searchform.subcat.options.length-1;j>=0;j--)
{
document.searchform.subcat.remove(j);
}


for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.searchform.subcat.options.add(optn);

} 
{
var optn2 = document.createElement("OPTION");

optn2.text = "Select Series";
optn2.value = '%';
document.searchform.subcat.options.add(optn2,0);
}
{
document.searchform.subcat.disabled=false;
document.searchform.subcat.selectedIndex = 0;

var defaultdd = "<?php echo $_SESSION['subcat'] ?>";
if (defaultdd != ""){
document.getElementById('s3').value = defaultdd;
}
}

      }
    }
    var url="dd2.php";
var cat_id=document.getElementById('name').value;
var cat_id2=document.getElementById('s2').value;
url=url+"?cat_id="+cat_id;
url=url+"&cat_id2="+cat_id2;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(url);
httpxml.open("GET",url,true);
httpxml.send(null);
  }
</script>

表单元素:

<form name="searchform" method='POST' action='?'>
  <table width="534" border="1" cellspacing="10" ID="tdspace">
    <tr>
      <td>Manufacturer: </td>
      <td><select name=name id='name' onchange=AjaxFunction();>
        <option value='%'>Select One</option>
        <?Php
try {
$dbo = new PDO('mysql:host=localhost;dbname='. $dbname, $username, $password);
} 
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}

$sql="SELECT Distinct Manufacturer FROM `tbl_Printers` order by `Manufacturer` asc ";
foreach ($dbo->query($sql) as $row) {

        if ($row[Manufacturer] == $_SESSION['name'])

        $selected = "selected=\"selected\"";
    else  
        $selected = "";
echo "<option value=$row[Manufacturer] $selected>$row[Manufacturer]</option>";
if( $_SESSION['type'])
{ echo '<script type="text/javascript">AjaxFunction()</script>';
}
}
?>
        <?php
    if ( $_SESSION['name'] == ""){ $namevalue = 'None Selected';}
    else {$namevalue = $_SESSION['name'];}

    if ( $_SESSION['type'] == "%"){ $typevalue = 'None Selected';}
    else {$typevalue = $_SESSION['type'];}

    if ( $_SESSION['subcat'] == "%"){ $subvalue = 'None Selected';}
    else {$subvalue = $_SESSION['subcat'];}
?>
      </select></td>
      <td>Manufacturer:<span style="color:cyan"> <?php echo $namevalue;?></span></td>
      </tr>
    <tr>
      <td>Product Type: </td>
      <td><select name=type id='s2' onchange=AjaxFunction2(); disabled=true>
        <option value='%' selected>Select Type</option>
      </select></td>
      <td>Product Type:<span style="color:magenta"> <?php echo $typevalue?></span></td>
      </tr>
    <tr>
      <td>Printer Catagory:</td>
      <td><select name=subcat id='s3' disabled=true>
        <option value='%' selected>Select Series</option>
      </select></td>
      <td>Printer Series:<span style="color:yellow"> <?php echo $subvalue;?></span></td>
      </tr>
    <tr>
      <td height="27" colspan="2" ID="centered" style="padding-left:90px"><br />        <input type=submit onclick="s3.disabled=false; s2.disabled=false" class="quick-search-button btn"/></td>
      <td>Records Found:<span style="color:black; text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4)"> <?php echo $_SESSION['totalrecords'];?></span></td>
      </tr>
    <tr>
      <td height="28" colspan="3" style="text-align:center"><br />
        *Manufacturer is Manditory, all other fields optional. </td>
      </tr>
  </table>

  <br />
<br />

<p><div id="finish">

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

这是一个 php 页面,它应该返回第一个下拉列表的结果,尽管第二个下拉表单实际上是相同的并且可以工作:

<?Php
@$cat_id=$_GET['cat_id'];
//$cat_id=2;


$dbhost_name = "localhost";
$database = "database";// database name
$username = "username"; // user name
$password = "password"; // password 

//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$str='';
$sql="SELECT Distinct Type FROM `tbl_Printers` where Manufacturer='$cat_id' order by Type asc";
foreach ($dbo->query($sql) as $row) {
$str=$str . "$row[Type]".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string

//$main = array($str);
echo json_encode($str); 
//echo $str;
?>

感谢任何帮助,我已经尝试过搜索,通常我不会寻求帮助,但这只是远远超出了我的理解。

目前,我已将所有 queires 替换为这样阅读(其中很多人正在考虑分页......)我不认为这是一个答案,尽管只是一种解决方法。

"SELECT Distinct Type FROM `tbl_Printers` where Manufacturer Like CONCAT('%', '$cat_id', '%') order by Type asc"

感谢 Vigor 为我指明了正确的方向。不幸的是,由于我的声誉,我无法选择评论作为答案或在明天之前发布我自己的问题的答案,但非常感谢您找到问题。

导致问题的代码行是:

echo "<option value=$row[Manufacturer] $selected>$row[Manufacturer]</option>";

需要改成这样才能根据需要添加引号并仍然选择正确的保存项目:

echo "<option value='" . $row['Manufacturer']."' ".$selected." >" . $row['Manufacturer'] . "</option>";

【问题讨论】:

  • 当您查看源代码并查看下拉菜单应该位于的部分时,实际发送到浏览器的内容是什么?有时错误消息会显示在 字段中。
  • 当我从浏览器查看源代码时,除了第一个下拉列表值之外,表单选项中没有任何显示。我可以看到页面上没有错误。就好像查询运行并且没有返回结果一样。但是一旦我从第一个下拉列表中选择一个没有空格的值,第二个就会被填充。
  • 我在页面上注意到了。我有一个部分发布了每个下拉选择的值,并且第二个单词没有被捕获。因此,如果您选择 Pitney Bowes,则只会将 Pitney 发布回页面。正如预期的那样,虽然从第二个下拉列表中选择的两个单词正在与两个单词一起发回。

标签: javascript php mysql get


【解决方案1】:

最好测试一下,但我认为JS应该用+号替换空字符串才能正确传递:

替换: var cat_id=document.getElementById('name').value;

有: var cat_id=document.getElementById('name').value.replace('/ /gi','+');

【讨论】:

  • JS选择间隔值时出错:[23:10:26.259] TypeError: myarray.split is not a function @oemalternatives.ca/printersearch.php:53
  • 查看这里的信息:stackoverflow.com/questions/10583055/… 可能有助于调试问题。
  • aler(myarray); 是什么?返回 var myarray = JSON.parse(httpxml.responseText);?
  • 好的,所以问题似乎出在脚本从元素中检索值时。我在之后发布了一个警报: var cat_id=document.getElementById('name').value;使用 var cat_id 并且只捕获第一个单词。所以我想我需要弄清楚如何捕捉这两个词或者为什么它只捕捉一个............
  • 发现问题: 应该是
【解决方案2】:

选项值应该加上引号,否则空格值不会被传递。

 <option value="Kyocera Mita" >Kyocera Mita</option>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 2011-03-11
    相关资源
    最近更新 更多