自学PHP,所以如果我犯了任何明显错误,请饶了我, 我试图动态创建一个手风琴,并在每个手风琴标题下面创建相应的内容,从相应的表创建(如果标题是玉米饼,下面的信息将来自tacos_info表)我提出的一些解决方案我不是确定,在mysqli查询中以cheifly方式传递一个变量值作为表名。
<?php
//initialize list
$res = mysqli_query("SELECT * FROM tables ORDER BY votes DESC");
//build the accordion header and div content in descending order
while($row= mysqli_fetch_assoc($res)){
//create value for SQL table name to build content
$dbname='$row['name']';
//create the accordion headers
$accordioncontent= '<h3>'.$row['name'].'</h3>';
//build the query that will be used to create the accordion content dynamically
$res2 = mysql_query("SELECT * FROM '$dbname' ORDER BY votes DESC");
//while loop to build the div content dynamically
while($row2= mysqli_fetch_assoc($res2)){
//dynamically create the list items i.e the accordion content
$ranks= '<li id="li $row2['id']">
<div class="tut-img">
<img src="<?php echo $row2['img']?>" width="50" height="70" alt="<?php $row['title']?>" />
</div>
<div class="title"><a href="<?php echo $row2['url']?>" target="_blank" title=""><?php $row2['title']?></a>
</div>
</li>';
}//close content while loop
//create the submit button that submits according to each accordion divs content
$submitbutton='';
//limit submissions to once per IP, per table
$voted=false;
$vcheck= mysqli_query("SELECT 1 FROM sort_votes
WHERE ip='".$_SERVER['REMOTE_ADDR']."'
AND date_submit=CURDATE()
AND Tablename='$dbname' "
);
if(mysqli_num_rows($vcheck)==1)
$voted=true;
//conditional to assign either a submit or edit
if(!$votedIFC){$submitbutton='<a href="" onmousedown="javascript:submitvote('$dbname');" class="button">Enter opinion<span></span></a>'}
else{$submitbutton='<a href="" onmousedown="javascript:editvote('$dbname');" class="button">Enter opinion<span></span></a>'}
//concatonate the div header with the div content
$accordioncontent .= '<div><ul class="sort" id="rank_ul">'$ranks'</ul><div class="button-holder">'$submitbutton'</div></div>';
}//close accordion while loop
//send all this data to the AJAX GET request
echo $accordioncontent;
?>
我正确地将这些值传递给查询吗?这是允许的吗?如果没有什么是更好的选择?任何和所有提示,输入和知识都非常感激。
答案 0 :(得分:1)
首先,我可以看到你有时会以一种奇怪的方式使用简单和双引号。您使用哪个IDE进行开发?我的第一个建议是,您将使用适当的编辑器来自动检查您的代码语法。 例如,这似乎很奇怪(难以准备好,肯定会在某一点产生错误):
'<li id="li $row2['id']"> ..... ';
在我看来,这里的正确语法是:
"<li id='li ".$row2['id']."'> .... ";
此处有更多详情:http://www.trans4mind.com/personal_development/phpTutorial/quotes.htm
现在回答您的问题,您似乎更关注将值传递给SQL查询的方式。如果您正在寻找最佳实践,那么我建议您使用php PDO。它是PHP和您的数据库之间的一个层,除其他外,确保您正确地将值传递给SQL(降低SQL注入的风险,引用问题等...)。
有关PDO的更多详细信息,请访问:http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
我的最后建议: