Query not inserting, but not giving error either - php

I got this query and it's not inserting into the database but it's not giving an error either.
try {
$sth = $Db->dbh->prepare("INSERT INTO users (username,password,email,phone,first_name) VALUES (:username,:password,:email,:phone,:firstname)");
$sth->execute(array(':username' => $username,':password' => $password, ':email' => $email,':phone' => $phone,':firstname'=>$firstname));
} catch(Exception $e) {
echo $e->getMessage();
exit();
}
I've tried inserting the query by command and it works fine. There are other insert queries on the site and those work fine too.. I'm not sure what I'm doing wrong here

Can you try something like this?
try
{
// Prepare Statement
if (!($stmt = $mysqli->prepare("INSERT INTO users (username,password,email,phone,first_name) VALUES (?,?,?,?,?)")))
throw new Exception("Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error);
// Bind Parms
if (!$stmt->bind_param("sssss", $username, $password, $email, $phone, $firstname))
throw new Exception("Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error);
// Execute Statement
if (!$stmt->execute())
throw new Exception("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
catch (Exception $ex) {
exit('Error: '. $ex->getMessage());
}
P.S. As TiiJ7 suggestion on the comment to your question, are those two columns perm and rank - are they nullable columns? if not, you might have to specify a value at the time of row insertion.
More info here: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Related

PHP PDO: Search array value inside of MySQL's JSON object

I got the following data in MySQL's JSON-type column:
{"2": [2, 3], "3": [29], "71": "test"}
I need to search array value inside of attribute "2", which works just fine when variables are placed inside the query, but not when using PHP's PDO arrays.
$field_id = 2;
$option_id = 2;
$query = "SELECT id FROM notes WHERE JSON_CONTAINS(data, '{\"$field_id\": $option_id }')";
try {
$stmt = $dbh->prepare($query);
$stmt->execute();
$used_qty = $stmt->rowCount();
} catch(PDOException $ex) {
echo 'Query failed: ' . $e->getMessage();
exit;
}
// $used_qty returns 1 which is correct;
Binding through array returns 0:
$query = "SELECT id FROM notes WHERE JSON_CONTAINS(data, '?')";
try {
$stmt = $dbh->prepare($query);
$stmt->execute(array('{"' . $field_id . '": ' . $option_id . '}"'));
$used_qty = $stmt->rowCount();
} catch(PDOException $ex) {
echo 'Query failed: ' . $e->getMessage();
exit;
}
Can't figure out what I missed here.
Please help. Thanks.
You quoted your placeholder:
$query = "SELECT id FROM notes WHERE JSON_CONTAINS(data, '?')";
^-^--
which means it's NOT a placeholder, it's a string containing a question mark.
Remove those quotes.
After enabling PDO exceptions:
$dbh = new PDO($dsn, $dsn_user, $dsn_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
I got clear error message saying that only value can be accepted as a second parameter:
Query failed: SQLSTATE[22032]: <>: 3141 Invalid JSON
text in argument 2 to function json_contains: "The document root must
not follow by other values." at position 8.
https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html#function_json-contains
But there is a third optional [path] parameter available: JSON_CONTAINS(json_doc, val[, path])
Which is exactly what I needed:
$query = "SELECT id FROM notes WHERE JSON_CONTAINS(data, ?, ?)";
try { $stmt = $dbh->prepare($query); $stmt->execute(array($option_id, '$."' . $field_id . '"')); $used_qty = $stmt->rowCount(); } catch(PDOException $ex) { echo 'Query failed: ' . $ex->getMessage(); exit; }
Thanks to Marc B.

Inserting Variable into MySQL database [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I'm trying to insert a variable into a mysql database. I've read the various posts about how to do this however these don't seem to work for me, the following code doesn't write anything to the database (the variable seems to break the query) however does if I don't use variables, can anyone tell me what I've doing wrong here?
$dbhost = 'zzzzzzzzz';
$dbuser = 'xxxxxxxxx';
$dbpass = 'yyyyyyyyy';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
// VARIABLE SETUP;
$variable = 'variable';
$variable = mysql_real_escape_string($variable);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO db_variables_insert'.
'(time, variable) '.
'VALUES ( "2016-02-19 04:23:44", '$variable')';
mysql_select_db('wwwwww');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
First of all, for your issue you could try:
$sql = "INSERT INTO db_variables_insert".
"(time, variable) ".
"VALUES ( '2016-02-19 04:23:44', '".$variable."')";
However, you could rewrite this more sane as a prepared statement like:
/* mysqli_* to connect - ** See note on PDO below ** */
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Prepared statement, stage 1: prepare */
$sql = "INSERT INTO db_variables_insert (time, variable) VALUES (?,?)";
if ($stmt = $mysqli->prepare($sql)) {
/* Prepared statement, stage 2: bind parameters and execute */
$time = '2016-02-19 04:23:44';
// Assuming you already define $variable here
if ($stmt->bind_param("ss", $time, $variable)) {
/* Here this bit ^ can be "i" (integer), "s" (string) etc */
$execute = $stmt->execute();
if($execute === FALSE) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
/* ^ you are done executing the sql if no errors */
} else {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
} else {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* explicit close recommended */
$stmt->close();
Notes:
/** Recommended: Connect with PDO **/
$conn = new PDO('mysql:host=localhost;dbname=my_db;charset=UTF-8','user', 'pwd');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
^ useful to visit and practice:
PDO Tutorial for MySQL Developers
Prepared Statements
You need to use . to concatenate strings in PHP, you can't just put the variable next to the string. And if the variable column is a string, you need to put its value in quotes.
$sql = 'INSERT INTO db_variables_insert'.
'(time, variable) '.
'VALUES ( "2016-02-19 04:23:44", "' . $variable'")';
You can also write this as a single string with variable substitution, using double quotes around the PHP string.
$sql = "INSERT INTO db_variables_insert
(time, variable)
VALUES ( '2016-02-19 04:23:44', '$variable')";

PHP PDO return a empty array the next day

I use php with PDO to manage a database with mysql. When I run the server I can read and insert data in the tables of my database, everything is correct. But, the next day I use my script, my code return a empty Array when I read and don't insert any data. Furthermore, my script don't throw any exception when does that, and I don't understand why.
I run my database connection with this code:
try {
$this->dataBase = new PDO('mysql:dbname=' . $this->dbName . ';host=' .
$this->host . ';port=' . $this->port,
$this->user, $this->pass);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
I get the data from my database with the code:
try {
$sql = $this->dataBase->prepare("SELECT username FROM teachers");
$sql->execute();
$result = $sql->fetchAll();
return $result;
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
$this->reconnect();
}
I do something wrong?

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 ?

PHP MYSQL error handling - prepared statements

I am trying to achieve secure queries using prepared statements:
if (!($stmt = $db->prepare($q['query1']))) {
myException("Prepare failed: (" . $db->errno . ") " . $db->error);
} else if (!$stmt->bind_param("si", $variable1, $variable2)) {
myException("Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error);
} else if (!$stmt->execute() || !$stmt->store_result()) {
myException("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
} else {
(...)
Is it the best way to do this? This code is unreadable. Can I use something like try catch block instead of if/else if? Will it work well?
As You suppose, this would be much clearer:
try {
$stmt = $db->prepare($q['query1']);
$stmt->bind_param("si", $variable1, $variable2);
$stmt->bind_param("is", $variable3, $variable4);
if($stmt->execute()) {
$stmt->store_result();
$stmt->bind_result($result);
$stmt->close();
} else {
throw new Exception("error");
}
} catch (\Exception $e) {
echo $e->getMessage();
}
[code has been edited due to OP request]
try {
$stmt = $db->prepare($q['query']);
$stmt->bind_param("s", $s);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($result);
if ($stmt->fetch()) {
$stmt->close();
return $result;
}
else
throw new Exception("error");
} catch (Exception $e) {
myExceptionHandler($e);
}
Will you accept that code? :)

Categories