Is one of these prepared statements better than the other?

I’ve seen a couple ways, and I am wondering which is best for PhP and MySql 5.7 ? Sorry if this is a stupid question.

<?php
	include_once 'includes/dbh.inc.php';

    $first = mysqli_real_escape_string($conn, $_POST['first']);
    $last = mysqli_real_escape_string($conn, $_POST['last']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $uid = mysqli_real_escape_string($conn, $_POST['uid']);
    $pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
	
	$sql = "INSERT INTO users (user_first, user_last, user_email, user_uid, user_pwd) VALUES (?, ?, ?, ?, ?);";
	$stmt = mysqli_stmt_init($conn);

	if (!mysqli_stmt_prepare($stmt, $sql)) {
		echo "SQL Error";
	} else {
		mysqli_stmt_bind_param($stmt, "sssss", $first, $last, $email, $uid, $pwd);
		mysqli_stmt_execute($stmt);
	}
?>

or…

$conn = new mysqli($dbServername, $dbUsername, $dbPassword, $dbName);
$team_id = 1;	

$games = array();
//DEFINE ALL FIELDS NEEDED FROM games TABLE with table prefix e.g. ga.id
$sql_find_team = "SELECT
	  sc.school
	, st.state
	, ma.mascot
	, ga.id 
	FROM schools AS sc
		LEFT JOIN states AS st
			ON st.id = sc.state_id
		LEFT JOIN mascots AS ma
			ON ma.id = sc.mascot_id
		LEFT JOIN games AS ga
			ON ga.home_id = sc.id OR ga.guest_id = sc.id 			
	WHERE sc.id = ?
	ORDER BY ga.week";

$query_find_team = $conn->prepare($sql_find_team);
$query_find_team->bind_param("s", $team_id);
$query_find_team->execute();
$result_find_team = $query_find_team->get_result();
$numofrows = $result_find_team->num_rows; 
if(!empty($numofrows)){
	while($row = $result_find_team->fetch_assoc()){
		$games[] = $row;
	}
}else{
	echo 'No team was found!';
} 			

What exactly are you asking to be compared? The first is an INSERT and the second is a SELECT so there will of course be differences, but I’m not understandating how one could be considered “best” over the other.

1 Like

The second version is better due to not distorting the data.

The only real difference is that the first one is using procedural style and the second one is using OO style. There’s really nothing different after that. Also if you are using prepared statements, don’t use real_escape_string anymore. real_escape_string is used to escape user input, but if you’re using prepared statements then you don’t need these as prepared statements do this already.

I would recommend getting used to OO style because you will most likely be working with objects a lot if you understand basic PHP.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.