Hola, necesito obtener el user_id del login actual para usarlo en una pagina.
Esta es la función que utilizo para el login:
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt
FROM members
WHERE email = ?
LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $username, $db_password, $salt);
$stmt->fetch();
// hash the password with the unique salt.
$password = hash('sha512', $password . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
¿Como podria usar el id en otra pagina?
Gracias!
Si utilizas
session_start();
en la otra página, tendrás las variables $_SESSION
Sabes que quiere decir:
CitarNotice: Array to string conversion in...
Asi es como lo tengo:
<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
sec_session_start();
$connectedUserID = $_SESSION['userID'];
$stmt = $mysqli->prepare("SELECT rc_usuario.*, rc_referidos.*
FROM rc_referidos
INNER JOIN rc_usuario ON rc_usuario.idUsuario = rc_referidos.idReferido
WHERE rc_referidos.idRedComercio2 = '$connectedUserID'");
$stmt->execute();
$stmt->store_result();
while ($stmt->fetch()) {
$stmt['idUsuario'];
$stmt['nombre'];
$stmt['apellidos'];
$stmt['status'];
¿Ves algún fallo? ¿el while y la forma de declarar ids esta bien?
Gracias!
Tus variables $_SESSION[] no concuerdan. En uno tienes userID y en el otro user_id. Por cierto, no se hace mencion a la funcion sec_session_start en ningun lado. (session_start() debe estar presente en los dos scripts a menos que uno incluya al otro)
Arreglado, gracias. sec_session_start es una funcion de functions.php
Ahora me da un error que antes no me daba...
CitarFatal error: Call to a member function execute() on a non-object in C:\xampp\htdocs\referral.php on line 22
la linea 22 es precisamente:
$stmt->execute();
Lo más probable es que el prepare haya fallado y haya devuelto FALSE.
Citarmysqli_prepare() returns a statement object or FALSE if an error occurred.
Agrega antes del $stmt->execute :
if(!$stmt){
echo $mysqli->error;
}
Por cierto deberías utilizar los parametros para evitar SQLi.
$stmt = $mysqli->prepare("SELECT rc_usuario.*, rc_referidos.*
FROM rc_referidos
INNER JOIN rc_usuario ON rc_usuario.idUsuario = rc_referidos.idReferido
WHERE rc_referidos.idRedComercio2 = ?");
$stmt->bind_param('s', $connectedUserID);
CitarFatal error: Cannot use object of type mysqli_stmt as array in C:\xampp\htdocs\referral.php on line 45
Por usar:
$stmt['idUsuario'];
¿Cual es la forma correcta? ¿Y para imprimirlos entre etiquetas html?
echo'<li><a>'.$stmt['idUsuario'].'</a></li>';
Gracias.
$stmt->execute(); //Executa la sentencia
$result = $stmt->get_result(); //Regresa un objeto tipo mysqli_result
while($row = $result->fetch_array()){
$row['idUsuario']; //Columna idUsuario
}
Muchas gracias ahora funciona todo perfectamente.