mysqli prepared statement fails - php

I'm using a prepared statement that fails and I don't know why (no error is returned)Here's my code:
$stmt = $db->prepare("SELECT id, temps, nom, classes FROM profs WHERE matiere = ? AND pass = 0");
if ( false===$stmt ) {
die('prepare() failed: ('.$db->errno.')' . htmlspecialchars($db->error));
}
$rc = $stmt->bind_param("s", $mat);
if ( false===$rc ) {
die('bind_param() failed: ('.$db->errno.')' . htmlspecialchars($stmt->error));
}
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed: ('.$db->errno.')' . htmlspecialchars($stmt->error));
}
This returns only: "prepare() failed: (0)"
Where's the problem?

SELECT id, temps, nom, classes FROM profs WHERE matiere = ? AND pass = 0
Is this query valid? Does the profs table exist, and do the columns (id, temps, nom, classes, matiere, pass) exist (and spelt correctly!)

Related

php, mysqli update with prepared statement not working

function update_review($link, $user_id, $game_id, $rating, $title, $review) {
$sql = "UPDATE reviews SET rating = ?, title = ?, review = ? WHERE user_id = ? AND game_id = ?";
$stmt = $link->prepare($sql);
if ( !$stmt ) {
die("could not prepare statement: " . $link->errno . ", error: " . $link->error);
}
$stmt->bind_param("sssii", $rating, $title, $review, $user_id, $game_id);
if ( !$stmt ) {
die("could not bind params: " . $stmt->error);
}
if ( !$stmt->execute() ) {
die("couldn't execute statement");
}
}
function update_review2($link) {
$sql = "update reviews set rating = \"43\", title = \"test\", review = \"blah\" where user_id = \"5\" and game_id = \"1\"";
$stmt = $link->prepare($sql);
if ( !$stmt ) {
die("could not prepare statement: " . $link->errno . ", error: " . $link->error);
}
if ( !$stmt->execute() ) {
die("couldn't execute statement");
}
}
var_dump($review_data);
// output = array(5) { ["user_id"]=> int(5) ["game_id"]=> int(1) ["rating"]=> string(2) "43" ["title"]=> string(4) "test" ["review"]=> string(4) "blah" }
update_review($link, $review_data['rating'], $review_data['title'], $review_data['review'], $review_data['user_id'], $review_data['game_id']);
Going to be honest, done the usual uni student thing and left the assignment to last min and regretting it again...
Anyways been trying to figure this out for a few hours now and i've come to a loss, ive made it work by not using prepared statements as you can see above in the update_review2 function however when using the prepared statements version update_review it does not affect any rows in the db. If anyone can offer a bit of help it will be greatly appreciated especially because the deadline is in 6 hours!
Based on your above code the function call to update_review() has variables in one order while the function itself is declared with variables in another order.
Because of that, you might be passing a string when the statement is expecting an int.

Error with transaction: beginTransaction() on a non-object

I`m working with PDO and prepare statements and now I want to implement transactions, but when I do it I get this error:
Call to a member function beginTransaction() on a non-object in
The code is:
include_once '../../includes/db_connect.php';
include_once '../../includes/psl-config.php';
$mysqli->query("SET NAMES 'utf8'");
date_default_timezone_set('America/Mexico_City');
$hora = date("d-m-Y g:i a");
$mysqli->beginTransaction();
//OBTENCIÓN DE LA INFORMACIÓN
$id = $mysqli->real_escape_string( $_POST["id"] );
$fechaEntrada = date("Y-m-d");
$estatus = "Disponible";
$idUser = $mysqli->real_escape_string( $_POST['idUser'] );
$idUser = $idUser . " " . $hora;
//SELECIONAR INFORMACIÓN DE LA MAQUINA A ENTRAR
$sqlMaquina = "SELECT tipo, clave FROM maquinas_orden_renta WHERE id = $id";
$res = $mysqli->query($sqlMaquina);
$rows = $res->num_rows;
if (!$res)
printf("Error message: %s\n", $mysqli->error);
$objMaquinaRenta = $res->fetch_object();
$tipoMaquina = $objMaquinaRenta->tipo;
$idMaquina = $objMaquinaRenta->clave;
$sql = "UPDATE maquinas_orden_renta SET entradaReal = ?, estatus = ?,updated_by = ? WHERE id = ?";
$stmt = $mysqli->prepare($sql);
if ( false === $stmt )
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
$rc = $stmt->bind_param('sssi', $fechaEntrada, $estatus, $idUser, $id );
if ( false === $rc )
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
$rc = $stmt->execute();
if ( false === $rc )
die('execute() failed: ' . htmlspecialchars($stmt->error));
else{
if ($tipoMaquina == "conID") {
$sql2 = "UPDATE maquinas SET estatus = ?, updated_by = ? WHERE IdMaquina = ?";
$stmt = $mysqli->prepare($sql2);
if ( false === $stmt )
die('prepare2() failed: ' . htmlspecialchars($mysqli->error));
$rc2 = $stmt->bind_param('ss', $estatus, $idUser, $idMaquina );
if ( false === $rc2 )
die('bind_param2() failed: ' . htmlspecialchars($stmt->error));
$rc2 = $stmt->execute();
if ( false === $rc2 )
die('execute2() failed: ' . htmlspecialchars($stmt->error));
else
echo "Éxito";
}
}
if (false === $rc AND false === $rc2) {
echo "exito";
$mysqli->commit();
}else{
$mysqli->rollBack();
echo "error: $error";
}
$stmt->close();
So, I don`t know if the function beginTransaction is wrong or something.
It has to be $mysqli->begin_transaction(); on the connection not the statement. With a transaction you want to do more than one single statement.
http://php.net/manual/en/mysqli.begin-transaction.php

Mysqli prepared statement issue with get_result

I have been using the traditional method of query db with out prepared statement. So decided to move to prepared statement now as below are my codes.
$link = new mysqli(dbHost, dbUser, dbPassword, dbDatabase);
if($link->connect_error) {
die('bind_param() failed: ' . htmlspecialchars($link->connect_error));
}
$stmt = $link->stmt_init();
$selectQuery1 ="Select * From tblUser Where tblUser.userName=? ";
$stmt1 = mysqli_prepare($link, $selectQuery1);
if ( false===$stmt1 ) {
die('stmt1 prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$rc1 = $stmt1->bind_param('s', $userName);
if ( false===$rc ) {
die('rc1 bind_param() failed: ' . htmlspecialchars($stmt1->error));
}
$execute1 = $stmt1->execute();
if ( false===$execute1 ) {
die('execute1 execute() failed: ' . htmlspecialchars($stmt1->error));
}
$store1=$stmt1->store_result();
if ( false===$store1 ) {
die('store1() failed: ' . htmlspecialchars($stmt1->error));
}
$count1=$stmt1->num_rows;
$result1 = $stmt1->get_result();
if ( false===$result1 ) {
die('result1 () failed: ' . htmlspecialchars($stmt1->error));
}
The query worked well till this line $count1=$stmt1->num_rows; and the moment I put this codes $result1 = $stmt1->get_result(); my page failed and I found out that I must now change to mysql native driver etc. My biggest worry is by changing the driver it might effect all my other existing application. So what is the best mechanism to mitigate is there any other method to retrieve the result or move to PDO ? I want to be able to use this mechanism mysql_fetch_array($result, MYSQL_ASSOC) to get my select results ?

Insert values with if condition with mysqli

I am trying to make register member page. If a new member insert an email which has been already exist, then there will be a notification saying that the email is exist. But if the email has not been exist, the values they insert in the form will be send to database.
I don't know what is wrong with my code bellow. It just blank and doesn't send anything to databse. I need a help.
<?php
//conection:
$link = mysqli_connect(".com","klaudia","intheclaud","elektro") or die("Error " . mysqli_error($link));
//consultation:
$member_id=$_GET['member_id'];
$member_name=ucwords(htmlspecialchars($_POST['member_name']));
$member_email=$_POST['member_email'];
$member_password=htmlspecialchars($_POST['member_password']);
$member_phone=$_POST['member_phone'];
$member_address_satu=ucwords(htmlspecialchars($_POST['member_address_satu']));
$member_address_dua=ucwords(htmlspecialchars($_POST['member_address_dua']));
$member_reference=$_POST['member_reference'];
$query = "SELECT * FROM member_registry WHERE member_email='$member_email '" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
if (mysqli_num_rows($result) > 0) {
echo "This email you are using has been registered before";
}
else {
mysqli_query($link, "INSERT INTO member_registry (
'member_id',
'member_name',
'member_email',
'member_password',
'member_phone',
'member_address_satu',
'member_address_dua',
'member_reference')
VALUES (0,1,2,3,4,5,6,7,8)";
?>
I have tried to check the connection and the database. Everything works fine here. When I insert someone name which has been in the table of the database, it will echo that the email already exist. and vice versa.
$query = "SELECT * FROM member_registry WHERE member_name='Klaudia '" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
if (mysqli_num_rows($result) > 0) {
echo "This email you are using has been registered before";
}
else {
echo "This email you are using has NOT been registered before";
}
[UPDATE]
mysqli_query($link, "INSERT INTO member_registry (
'member_id',
'member_name',
'member_email',
'member_password',
'member_phone',
'member_address_satu',
'member_address_dua',
'member_reference')
VALUES (0,1,2,3,4,5,6,7,8)");
}
?>
You shouldn't handle this by two separate queries (at least without a transaction).
Instead create a unique index that doesn't allow the same email address twice in the table and check for the specific ER_DUP_ENTRY error code to detect doublets.
sscce:
<?php
define('MYSQL_ER_DUP_ENTRY', 1062);
$mysqli = new mysqli('localhost', 'localonly', 'localonly', 'test');
if ($mysqli->connect_errno) {
trigger_error('connection failed', E_USER_ERROR);
}
$result = $mysqli->query('
CREATE TEMPORARY TABLE soFoo (
id int auto_increment,
email varchar(128),
primary key(id),
unique key(email)
)'
);
if ( !$result) {
trigger_error('create table failed', E_USER_ERROR);
}
$stmt = $mysqli->prepare('INSERT INTO soFoo (email) VALUES (?)');
if (!$stmt) {
trigger_error('prepare failed', E_USER_ERROR);
}
$result = $stmt->bind_param("s", $email);
if ( !$result) {
trigger_error('bind_param failed', E_USER_ERROR);
}
foreach( array('email1', 'email2', 'email1') as $n=>$email ) {
echo $n, ' ', $email;
$result = $stmt->execute();
if ( $result ) {
echo " ok\r\n";
}
else {
if ( MYSQL_ER_DUP_ENTRY==$stmt->errno ) { // <-- here's the test for the duplicate entry
echo " duplicate\r\n";
}
else {
var_dump($stmt->errno, $stmt->error);
}
}
}
prints
0 email1 ok
1 email2 ok
2 email1 duplicate
You have an error in your syntax. You don't close your function.
Also you shouldn't use single quotes around your coumn names.
mysqli_query($link, "INSERT INTO member_registry (
`member_id`,
`member_name`,
`member_email`,
`member_password`,
`member_phone`,
`member_address_satu`,
`member_address_dua`,
`member_reference`)
VALUES (0,1,2,3,4,5,6,7,8)");

Error: You have an error in your SQL syntax at line 1 INSERT INTO

I'm trying to insert a row into a table. Well, the page add the row, but when it does, appears a MySQL error, something like this:
Error: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '1' at line 1
This is my PHP code:
<?php
$lang = "english";
header('Content-Type: text/html; charset=UTF-8');
require '../security.php';
$con=mysqli_connect($sec[0],$sec[1],$sec[2],$lang);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!$con->set_charset("utf8")) {
} else {
}
$result = mysqli_query($con,"INSERT INTO `ta_exp` (`date`, `cargo`, `DP`, `LP`, `url`)
VALUES ('".mysqli_real_escape_string($con,$_GET['date_exp'])."','".mysqli_real_escape_string($con,$_GET['cargo_exp'])."','".mysqli_real_escape_string($con,$_GET['lp_exp'])."','".mysqli_real_escape_string($con,$_GET['dp_exp'])."','".mysqli_real_escape_string($con,$_GET['url'])."')");
if (!mysqli_query($con,$result)) {
die('Error: ' . mysqli_error($con));
}
echo "added";
mysqli_close($con);
?>
mysqli_prepare is the way to go:
$query = "INSERT INTO `ta_exp` (`date`, `cargo`, `DP`, `LP`, `url`)
VALUES (?, ?, ?, ?, ?)";
if ($stmt = mysqli_prepare($con, $query)) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "sssss", $_GET['date_exp'],
$_GET['cargo_exp'],
$_GET['lp_exp'],
$_GET['dp_exp'],
$_GET['url']);
/* execute query */
mysqli_stmt_execute($stmt);
}
Finally my code seems like this:
$con = new mysqli($sec[0],$sec[1],$sec[2],$lang);
if ($con->connect_error) {
trigger_error('Database connection failed: ' . $con->connect_error, E_USER_ERROR);
}
if (!$con->set_charset("utf8")) {
} else {
}
$sql = "INSERT INTO experiences (`date`, `cargo`, `DP`, `LP`, `url`)
VALUES ('".mysqli_real_escape_string($con,$_GET['date_exp'])."','".mysqli_real_escape_string($con,$_GET['cargo_exp'])."','".mysqli_real_escape_string($con,$_GET['lp_exp'])."','".mysqli_real_escape_string($con,$_GET['dp_exp'])."','".mysqli_real_escape_string($con,$_GET['url'])."')";
if($con->query($sql) === false)
{
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->error, E_USER_ERROR);
} else {
$last = $con->insert_id;
$aff = $con->affected_rows;
}
$con->close();

Categories