Execute Multiple Queries in PHP with NULL as an Input Parameter - php

EDIT (2011-07-23)
Have gotten some very helpful answers, both of which I've tried implementing. But I can't seem to get back the id from my Get_Security statement. I'm pretty sure my problem is that, in my first call statement Get_Security, the last three parameters are set to NULL. Seems like other people have the same problem. Doesn't seem like there's much documentation on having NULL as an input. How does one go about this?
NEW CODE
$stmt = mysqli_stmt_init($link);
$sql = "CALL Get_Security('$symbol', '$tagName', NULL, NULL, NULL)";
if (!mysqli_stmt_prepare($stmt, $sql)){
$error = 'Failed to prepare statement. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
}
mysqli_stmt_close($stmt);
mysqli_close($link);
include $_SERVER['DOCUMENT_ROOT'] . 'mypath-to-database-link'; //this gets $link
$stmt = mysqli_stmt_init($link);
$sql = "CALL Add_Active('$id','Research')";
if (!mysqli_stmt_prepare($stmt, $sql)){
$error = 'Failed to prepare statement Add_Active. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
include $_SERVER['DOCUMENT_ROOT'] . 'mypath-to-database-link'; //this gets $link
$sql = "INSERT INTO MyTable SET
id='$id',
open_items='$openItems',
attachments='$attachments'
";
$stmt = mysqli_stmt_init($link);
if (!mysqli_stmt_prepare($stmt, $sql)){
$error = 'Failed to INSERT INTO Research_Security. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
ORIGINAL ENTRY
Searched extensively (e.g. PHP Manual, SO questions) but answers are confusing.
I need to execute 3 of SQL statements in a row:
Call stored procedure Get_Security that takes some inputs and returns an array, including the id.
Call another stored procedure Add_Active that takes the returned id from Get_Security as an input.
Insert some variables into my table.
Problem: I'm getting the MySQL Error Number 2014: "Commands out of sync; you can't run this command now".
I know I have to use mysqli_stmt_prepare, mysqli_stmt_execute, and mysqli_stmt_close to resolve this, but it's very confusing how to do this.
Would very much appreciate help in how to translate this using the above functions.
CODE:
$sql = "CALL Get_Security('$symbol', '$tagName', NULL, NULL, NULL)";
$result = mysqli_query($link, $sql);
if (!$result){
$error = 'Error calling stored procedure Get_Security.';
include '../error.html.php';
exit();
}
while($row = mysqli_fetch_array($result)){
$tags[] = array('id' => $row['id']);
}
foreach ($tags as $tag){
$id = $tag['id'];
}
$sql = "CALL Add_Active('$id','Research')";
$result = mysqli_query($link, $sql);
if (!$result){
$error = 'Error calling stored procedure Add_Active. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
$sql = "INSERT INTO MyTable SET
id='$id',
open_items='$openItems',
attachments='$attachments'
";
if (!mysqli_query($link, $sql)){
$error = 'Error adding submitted tag into Research_Security. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}

I hope this helps. From what I can tell you aren't doing anything too fancy, so this should suffice. PDO does also support IN/OUT params to stored procedures as well, but I didn't see you using them.
Please note, PDO handles errors in different ways depending on how it is initialized. So I've skipped error handling here. Please let me know if you have questions.
Also note that until you add a DSN (MySQL's for example) this code doesn't care what database type it is, so the DSN can be a config value making your code more portable. I'm sure you could also see how this code could easily be expanded into a class/model structure (specifically the security check SP could become a PHP method)
$db = new PDO(); // http://www.php.net/manual/en/pdo.construct.php for params
// These generate PDO_Statement (see: http://www.php.net/manual/en/class.pdostatement.php)
$securityStmt = $db->prepare("CALL Get_Security( ?, ?, ?, ?, ? )");
$addActiveStmt = $db->prepare("CALL Add_Active( ?, ? )");
$insertStmt = $db->prepare("INSERT INTO MyTable SET id=?, open_items=?, attachments=?");
// Security CALL
$securityStmt->bindParam( 1, $symbol, PDO::PARAM_STR );
$securityStmt->bindParam( 2, $tagName, PDO::PARAM_STR );
$securityStmt->bindParam( 3, NULL, PDO::PARAM_NULL );
$securityStmt->bindParam( 4, NULL, PDO::PARAM_NULL );
$securityStmt->bindParam( 5, NULL, PDO::PARAM_NULL );
$securityStmt->execute();
// Bind the ID to a variable is useful sometimes...
$securityStmt->bindColumn( 'id', $securityId );
$securityStmt->fetch( PDO::FETCH_BOUND );
/*
Insert + Active call
These are much simpler because we don't need to set the data types of the input
(they are all string I hope...you didn't mention what the last 2 were in the insert).
*/
$addActiveStmt->execute(
array(
$securityId,
'Wedge Research'
)
);
$insertStmt->execute(
array(
$securityId,
$openItems,
$attachments
)
);

$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, "CALL SOMETHING()");
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
print_r($row);
}
mysqli_stmt_close($stmt);

So I've figured out how to solve this with my original code by simply closing the link to the database after every query. I would love to do prepared statements instead, but at least this works.
include $_SERVER['DOCUMENT_ROOT'] . 'path-to-connecting-to-db'; //get $link here
$sql = "CALL Get_Security('$symbol', '$tagName', NULL, NULL, NULL)";
$result = mysqli_query($link, $sql);
if (!$result){
$error = 'Error calling stored procedure Get_Security.';
include '../error.html.php';
exit();
}
while($row = mysqli_fetch_array($result)){
$tags[] = array('id' => $row['id']);
}
foreach ($tags as $tag){
$id = $tag['id'];
}
mysqli_close($link);
include $_SERVER['DOCUMENT_ROOT'] . 'path-to-connecting-to-db'; //get $link here
$sql = "CALL Add_Active('$id','Research')";
$result = mysqli_query($link, $sql);
if (!$result){
$error = 'Error calling stored procedure Add_Active. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}
mysqli_close($link);
include $_SERVER['DOCUMENT_ROOT'] . 'path-to-connecting-to-db'; //get $link here
$sql = "INSERT INTO myTable SET
id='$id',
open_items='$openItems',
attachments='$attachments'
";
if (!mysqli_query($link, $sql)){
$error = 'Error adding submitted tag into Research_Security. Error No: ' . mysqli_errno($link) . ': ' . mysqli_error($link);
include '../error.html.php';
exit();
}

Related

binding parameters in MySQl and PHP

I am trying to learn how to use prepared statements in my PHP, to get data out from MySQL database. At the moment I am not getting anything printed out.
I need to have a while loop there is going through my rows in the database. Is that correct?
Am I on the correct way here, or what am I missing? I made some comments in the code, to describe what I am doing.
<?php
$stmt = $mysqli->prepare("SELECT * FROM fantasies WHERE headline = ? AND description = ? AND place = ? ORDER BY reg_date DESC LIMIT 3");
// Execute prepared statement
if ($stmt->execute()) {
$success = true;
}
// Make variables ready
$head = null;
$desc = null;
$plac = null;
// Bind result to variables
$stmt->bind_result($head, $desc, $plac);
while ($stmt->fetch()) {
// What should go here?
echo "Headline: ".$head."Description: ".$desc."Place: ".$place;
}
// Close statement
$stmt->close();
// Close connection
$mysqli->close();
if($success) {
echo "Selected Succesfull";
} else {
echo "Failed: " . $stmt->error;
}
}
?>
That code when executed it should give you an error :
Invalid parameter number: no parameters were bound
You need to bind your parameters as you are using placeholders
$stmt->bind_param("sss", $headline, $description, $place); //missing from your code
where "sss" is the dataType in this case a string and $headline, $description, $place are your variables that you replacing with placeholders
Your code should be
<?php
$stmt = $mysqli->prepare("SELECT * FROM fantasies WHERE headline = ? AND description = ? AND place = ? ORDER BY reg_date DESC LIMIT 3");
//bind parameters
$stmt->bind_param("sss", $headline, $description, $place);
if ($stmt->execute()) {
$stmt->bind_result($head, $desc, $plac);
while ($stmt->fetch()) {
echo "Headline: " . $head . "desc: " . $desc . "Place: " . $plac;
}
$stmt->close();
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
?>

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.

php script wont add record to mysql

The first example will add data to mysql database without any issue. The second block of code - where I try to use variables wont. Can someone please explain where I am going wrong?
<?php
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES ('Edit me',4,1)";
$result = mysqli_query($connection, $query);
Problem CODE:
<?php
$menu_name = "TEST";
$position = 5;
$visible = 1;
$query = "INSERT INTO subjects (menu_name,position,visible)
VALUES ('{menu_name}',{position}, {visible})";
$result = mysqli_query($connection, $query);
*Answer updated with MySQLi prepare statement, thanks #h2ooooooo
<?php
//Open a new connection to the MySQL server
$db = new mysqli('host','username','password','database_name');
//Output connection errors
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
$sql = "INSERT INTO subjects (menu_name, position, visible) VALUES (?, ?, ?)";
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
$stmt->bind_param('sss', $menu_name, $position, $visible);
if (!$stmt->execute()) {
echo 'Database execute error';
exit;
}
$stmt->close();
I'd say for you to take a look in the many tutorials thorugh net, like these:
http://markonphp.com/simple-insert-mysqli/ and
http://www.sanwebe.com/2013/03/basic-php-mysqli-usage
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES
('".$menu_name."','".$position."', '".$visible."')";
try this

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();

Using isset for correction?

I'm new to PHP,I got error in my web page.It said:
Notice: Undefined index: itemid in /home/tz005/public_html/COMP1687/edit.php on line 103
Can I use isset to fix this problem? If yes, how to do so? Here is my script:
<?php
//include database connection
include 'dbconnect.php';
// if the form was submitted/posted, update the item
if($_POST){
//write query
$sql = "UPDATE
item_information
SET
itemtitle = ?,
itemdescription = ?,
date = ?,
WHERE
itemid= ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param(
'sssi',
$_POST['itemtitle'],
$_POST['itemdescription'],
$_POST['date'],
$_POST['itemid']
);
// execute the update statement
if($stmt->execute()){
echo "Item was updated.";
// close the prepared statement
$stmt->close();
}else{
die("Unable to update.");
}
}
$sql = "SELECT
itemid, itemtitle, itemdescription, date
FROM
item_information
WHERE
id = \"" . $mysqli->real_escape_string($_GET['itemid']) . "\"
LIMIT
0,1";
// execute the sql query
$result = $mysqli->query( $sql );
//get the result
if ($result = $mysqli->query( $sql )) {
if ($row = $result->fetch_assoc()) {
// $row contains data
}
}
//disconnect from database
$result->free();
$mysqli->close();
?>
change
$mysqli->real_escape_string($_GET['itemid'])
to
$mysqli->real_escape_string($_POST['itemid'])
or use empty() or isset() to check values exist
Yes you can do it with isset() function
Create conditions for it
if(isset($_GET['itemid'])){
//execute your code
}
else{
//header them back to page or show error that itemid not set or something else whatever suits you
}

Categories