2014-01-13 3 views
2

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

По умолчанию процедурного сценарий Mysqli по умолчанию

<?php 
$conn = mysqli_connect ('localhost', 'gggggg', 'gggggg') ; 
mysqli_select_db ($conn, 'ggggg'); 

$anti_injection = mysqli_real_escape_string($_GET['user']); 

$sql = "SELECT * FROM profiles WHERE username =".$anti_injection); 
$result = mysqli_query($conn, $query); 

while($row = mysqli_fetch_array($sql)) { 

$username = stripslashes($row['username']); 
$age = stripslashes($row['age']); 
$gender = stripslashes($row['gender']); 
?> 


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>title</title> 
</head> 

<body> 
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC... 

    CATEGORY <?php echo $username; ?> 
    TITEL <?php echo $age; ?> 
    CONTENT <?php echo $sex; ?> 

</body> 
</html> 
<?php 
} 
?> 
#

ТЕПЕРЬ МОИ ИЗМЕНЕНИЯ В ОТЧЕТНОСТИ НАДЕЮТСЯ ЭТО РАБОТАЕТ

#
$query = $sql->prepare("SELECT * FROM profiles WHERE `username`=?") 
$prep->bind_param("s",$anti_injection); 
$prep->execute(); 

Thats все, что я знаю для SELECT в безопасном режиме, но затем с MYSQLI_FETCH_ARRAY. Я действительно не знаю, что это сработает и, надеюсь, если есть шанс сохранить сценарий так, как мне нравится, с помощью ech os между HTML BODY страница

Пример: Как это сделать?

+0

Интересно, что такое переменная $ prep? –

+0

http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php –

+0

даже не знаю этого. Я просто скопировал их из другого примера, и я пытаюсь понять, как это делается без везения :( – Firefighter

ответ

1

Прежде всего, I высоко рекомендовать вам не смешивать процедурные с объектами. Это будет запутывать намного быстрее таким образом. Вместо этого используйте вместо этого объект mysqli.

$mysqli = new mysqli('localhost'...); 

Во-вторых, вы близки, но, как я уже говорил, вы смешиваете объекты и процедурный так, как вы изменили это не будет работать. Кроме того, вы повредите переменные повсюду (если вы запустили свои изменения, они не сработают). Предполагая, что вы переключитесь на mysqli объекта, как описано выше, вы можете сделать это

$prep = $mysqli->prepare("SELECT * FROM profiles WHERE `username`=?"); 
$prep->bind_param("s",$anti_injection); 
$prep->execute(); 

Теперь следующая часть сложнее. У вас должно быть установлено mysqlnd, но это лучший способ вернуть результаты. Если запустить это и получить ошибку о get_result неведения, вы не работаете mysqlnd

$result = $prep->get_result(); 
while($row = $result->fetch_array()) { 
    //Your HTML loop here 
} 
+0

. Я попытаюсь посмотреть, разрешено ли его включение. m8 – Firefighter

+0

Не повезло. Неустранимая ошибка: вызов неопределенного метода mysqli_stmt: : get_result() в – Firefighter

+0

Тогда главный облом.Если вы не можете изменить свою серверную среду, вам придется использовать значительно clunkier [bind_result] (http://us3.php.net/manual/en/mysqli-stmt.bind-result.php) – Machavity

0

вы можете сделать это, что

$link = mysqli_connect("localhost", "my_user", "my_password", "db"); //Establishing connection to the database , this is alias of new mysqli('') 
$query="SELECT * FROM profiles WHERE `username`=?"; 
$stmt = $link->prepare($query); 
$stmt->bind_param("s",$anti_injection); // binding the parameter to it 
$stmt->execute(); //Executing 
$result = $stmt->get_result(); 
while($row = $result->fetch_array(MYSQLI_ASSOC)) // we used MYSQLI_ASSOC flag here you also can use MYSQLI_NUM or MYSQLI_BOTH 
{ 
//Do stuff 
} 
+0

Я буду дайте ему тест прямо сейчас, задаваясь вопросом, почему # query = "SELECT * FROM profiles WHERE' username' =? " вы отредактировали с символом # – Firefighter

+0

Извините, это опечатка, я исправлю ее прямо сейчас –

+0

Пробовал и даже Dreamweaver дает мне ошибку на подобном запросе из профилей ... Кажется, что какой-то символ отсутствует – Firefighter

0

Если you'r обучения я призываю вас использовать Object Oriented Style

Manual - это первый ресурс, где вы можете найти самую точную информацию. После вашего примера:

$mysqli = new mysqli("example.com", "user", "password", "database"); 
if ($mysqli->connect_errno) { 
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; 
} 

//Here you avoid the warning undefine variable if $_GET['user'] ins't set 
$user = isset($_GET['user']) ? $_GET['user'] : NULL; 
$row = array(); 

//Checking if $user is NULL 
if(!empty($user)){ 
    // Prepared statement, stage 1: prepare 
    if (!($stmt = $mysqli->prepare("SELECT * FROM profiles WHERE `username`=?"))) { 
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error; 
    } 
    /* Prepared statement, stage 2: bind and execute */ 
    if (!$stmt->bind_param("s", $user)) { 
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error; 
    } 
    if (!$stmt->execute()) { 
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; 
    } 
    //Fetching the result 
    $res = $stmt->get_result(); 
    $row = $res->fetch_assoc(); 
    /* explicit close recommended */ 
    $stmt->close(); 
}else{ 
//do this code if $user is null 
} 


//Printing out the result 
echo '<pre>'; 
print_r($row); 
echo '</pre>'; 
0

я обеспечиваю сценарий, основанный на ваших, что я заметил, протестирован и использует процедурную «Mysqli». Надеюсь, это прояснит ситуацию.

<?php 
/* (PHP 5.3.18 on XAMPP, windows XP) 
* 
* I will use the procedural 'mysqli' functions in this example as that is 
* what you seem familiar with. 
* 
* However, the 'object oriented' style is preferred currently. 
* 
* It all works fine though :-) 
* 
* I recommend PDO (PHP Data Objects) as the way to go for Database access 
* as it provides a 'common' interface to many database engines. 
*/ 


// this is an example 'select' parameter -- how this value gets set is up to you... 
// use a form, get parameter or other, it is not important. 

$bindparamUsername = 'user_2'; // example!!!! 

// connect to the database... 
$dbConnection = mysqli_connect('localhost', 'test', 'test'); // connect 
mysqli_select_db($dbConnection, 'testmysql'); // my test database 


// the SQL Query... 

// the '?' is a placeholder for a value that will be substituted when the query runs. 
// Note: the ORDER of the selected Columns is important not the column names. 
// 
// Note: The number of selected columns is important and must match the number of 
// 'result' bind variables used later. 

$sql = "SELECT username, age, gender FROM profiles WHERE username = ?"; 

// DB engine: parse the query into an internal form that it understands 
$preparedQuery = mysqli_prepare($dbConnection, $sql); 

// bind an actual input PHP variable to the prepared query so the db will have all required values 
// when the query is executed. 
// 
mysqli_stmt_bind_param($preparedQuery, 's', $bindparamUsername); 

// run the query... 
$success = mysqli_execute($preparedQuery); 


// You can only bind which variables to store the result columns in AFTER the query has run! 
// 

// Now bind where any results from the query will be returned... 
// There must be as many 'bind' variables as there are selected columns! 
// This is because each column value from the query will be returned into the 
// 'bound' PHP variable. 
// 
// Note: You cannot bind to an array. You must bind to an individual PHP variable. 
// 
// I have kept the same names but they are only of use to you. 
$fetchedRow = array('username' => null, 
        'age'  => null, 
        'gender' => null); 


/* 
* Note: order of columns in the query and order of destination variables in the  'bind' statement is important. 
* 
* i.e. $fetchedRow[username] could be replaced with variable $firstColumn, 
*  $fetchedRow[age] could be replaces with variable $secondColumn 
* and so on... 
*  
* There must be as many bind variables as there are columns.    
*/ 
mysqli_stmt_bind_result($preparedQuery, $fetchedRow['username'], 
             $fetchedRow['age'], 
             $fetchedRow['gender']); 

/* 
* Note: if you use the 'Object Oriented' version of 'mysqli': All of this is 'hidden' 
*  but still happens 'behind the scenes'! 
* 
*/ 
?> 

<!DOCTYPE html> 
<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title></title> 
    </head> 
    <body> 
    CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC... 

    <?php // each 'fetch' updates the $fetchedRow PHP variable... ?> 
    <?php while (mysqli_stmt_fetch($preparedQuery)): ?> 
     <br /> 
     CATEGORY <?php echo $fetchedRow['username']; ?> 
     <br /> 
     TITEL <?php echo $fetchedRow['age']; ?> <br /> 
     CONTENT <?php echo $fetchedRow['gender']; ?> <br /> 
    <?php endwhile ?> 

    </body> 
</html> 
+0

Я буду тестировать его, но выглядит действительно взволнованным и легкомысленным, спасибо за ваше время – Firefighter

+0

получил сообщение об ошибке http://chilecell.com/BOMBERIL/cague.php?username=juan – Firefighter

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