running a mysql stored procedure from php - php

I must be doing something wrong in this code....
<?
$codeid=$_GET["codeid"];
$tablecode=$_GET["tablecode"];
$description=$_GET["description"];
$code=$_GET["code"];
$groupcode=$_GET["groupcode"];
$t1=$_GET["t1"];
$t2=$_GET["t2"];
$t3=$_GET["t3"];
$mysqli = new mysqli(dbhost,dbuser,dbpass,dbc);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$q="call spUpdateCodeTable(?,?,?,?,?,?,?,?)";
$stmt = $mysqli->prepare($q);
$stmt->bind_param($codeid,$tablecode,$description,$code,$groupcode,$t1,$t2,$t3);
$stmt->execute();
mysql_close($mysqli);
?>
Absolutely nothing happens...no error message or any other indication of a problem. It just does not run the procedure. (it's an update/insert routine).
I am using this URL...
updateCodeTable.php?codeid=0&codetable=TABLE&desription=testing2%20entry&code=TEST1&groupcode=gcode&t1=t1&t2=t2&t3=t3
...but, if I run the this query in phpMyAdmin, it runs perfectly....
call spUpdateCodeTable(0,'TABLE','testing2','TEST1','group','','','');
I could include the stored procedure code, but it runs fine anytime I run it directly, but just not running successfully from my php code.

Each mysqli* function/method can fail. Either test the return values and/or switch the reporting mechanism to exceptions, see http://docs.php.net/mysqli-driver.report-mode
<?php
// probably better done with http://docs.php.net/filter but anyway ...just check whether all those parameters are really there
// you are positive that GET is the correct method for this action?
if ( !isset($_GET["codeid"], $_GET["tablecode"], $_GET["description"], $_GET["code"], $_GET["groupcode"], $_GET["t1"], $_GET["t2"], $_GET["t3"]) ) {
// die() is such a crude method
// but bare me, it's just an example....
// see e.g. http://docs.php.net/trigger_error
die('missing parameter');
}
else {
$mysqli = new mysqli(dbhost,dbuser,dbpass,dbc);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$q="call spUpdateCodeTable(?,?,?,?,?,?,?,?)";
$stmt = $mysqli->prepare($q);
if ( !$stmt ) {
// $mysqli->error has more info
die('prepare failed');
}
// you have to provide the format of each parameter in the first parameter to bind_param
// I just set them all to strings, better check that
if ( !$stmt->bind_param('ssssssss', $_GET['codeid'], $_GET['tablecode'], $_GET['description'], $_GET['code'], $_GET['groupcode'], $_GET['t1'], $_GET['t2'], $_GET['t3']) ) {
// $stmt->error has more info
die('bind failed');
}
if ( !$stmt->execute() ) {
// $stmt->error has more info
die('execute failed');
}
}

May you have a try to this?
mysqli->query("call spUpdateCodeTable($codeid,'$tablecode',
'$description','$code','$groupcode','$t1','$t2','$t3')");

Related

Issue getting mysqli_query to execute

I have written the following function in PHP that has a mysqli_query in it that runs without any errors or exceptions. However, the INSERT INTO statement or $insert variable doesn't seem to be working as expected and I can't figure it out. I realize that posting only a portion of the code might make it difficult to ascertain why it is not working, but I am really looking for confirmation that there are no errors in this function.
Do I need to utilize mysqli_real_escape_string for every url provided? I tried altering $website to $_website to account for this, but it returned nothing.
Just really trying to figure out if there's anything I'm doing wrong here that's prevent the SQL query to work. It returns no error which is making it hard to debug. Thanks in advance!
$jp = mysqli_connect("localhost", "myuser", "password", "mydatabase");
if (!$jp) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
function create_distributor( $new_user_id ) {
$errors = new WP_Error();
$error=false;
$errorMsg='';
$logo=true;
$name=addslashes(htmlentities($_REQUEST['name']));
$contact=addslashes(htmlentities($_REQUEST['contact_info']));
$user_info = get_userdata( $new_user_id );
$website = $_POST['website'];
if (stripos($website, "http://") !== 0) //doesn't start with http:// ? , then add it
$website = "http://" . $website;
// $_website = mysqli_real_escape_string($jp, $website); // THIS DOESNT RETURN ANYTHING
$subdir = $user_info->user_nicename; // use nicename because user_login is obfuscated as unverified
$distribpath = 'http://ghq.com/dhdq/'.$subdir;
$ga_code = 'UA-15331916-1'; //default GA code
$logo = 'http://ghq.com/wp-content/themes/CAG/img/ghlogo.jpg'; //default png logo
if(!isset($_REQUEST['name']) || $_REQUEST['name']=='')
{
$error=true;
$errors->add('Distributor Name is required', __('<strong>ERROR</strong>:Distrubutor\'s name was not provided.'));
}
if($error)
{
return($errorMsg);
}
$insert="INSERT INTO distributor (id, name, contact, logo, path, subdir, website, ga_code) VALUES ('".$new_user_id."','".$name."','".$contact."','".$logo."','".$distribpath."','".$subdir."','".$website."','".$ga_code."')";
// var_dump($insert);
// The var_dump print out above is the following SQL Command which if copied and pasted
in phpmyadmin works fine: string(252) "INSERT INTO distributor (id, name, contact,
logo, path, subdir, website, ga_code) VALUES ('1748','test24','','http://ghq.com/wp-content/themes/CAG/img/ghlogo.jpg',
'http://ghq.com/dhdq/test24','test24','','UA-15331916-1')"
mysqli_query($jp, $insert);
if ( false===$insert ) {
printf("error: %s\n", mysqli_error($jp));
}
else {
echo 'done.';
}
if($error)
{
return $errors;
}
else
{
return($id);
}
}
The problem I can see straight off is you are checking your sql variable instead of the query result.
mysqli_query($jp, $insert);
if ( false===$insert ) {
printf("error: %s\n", mysqli_error($jp));
}
else {
echo 'done.';
}
Try changing it to:
$result = mysqli_query($jp, $insert);
if (!$result) {
printf("error: %s\n", mysqli_error($jp));
}else {
echo 'done.';
}
Also whats $jp? it doesn't look like you have assigned it anything. Make sure this is the variable that has your mysqli_connect on it. With your question regarding mysqli_real_escape_string, you should really be utilizing mysqli prepared statements as well. All user input should be sanitized.

Why this PHP Code won't add the data to the MySQL DB?

I am brand new in PHP / MySQL.
I got this code from
http://www.johnmorrisonline.com/how-to-insert-form-data-into-a-mysql-database-using-php/
(great tutorial by the way) and used it. The problem is that it runs smoothly (Got no errors) but it just won't add the new row to the database. I tried to simplify the code to figure it out. If i run the query on PHPMyAdmin it works ok (it adds a new row) but from browser (php script) won't.
I cant tell what's wrong.
I am using MAMP on my MBP computer.
Thanks so much
Rafa
Here's the code:
<?php
$mysqli = mysqli_init();
if (!$mysqli) {
die('mysqli_init failed');
}
if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!$mysqli->real_connect('localhost', 'root', 'root', 'procedimientos')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . $mysqli->host_info . "\n";
// Insert our data
$sql = "INSERT INTO PROCEDIMIENTOS (`RUT`) VALUES ('1587');";
$insert = $mysqli->query($sql);
// Print response from MySQL
if ( $insert ) {
echo "Success!";
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
$mysqli->close();
?>
You have to add $mysqli->commit(); before $mysqli->close(); to persist your changes to the DB.
You have this on top of your code:
if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
In other words, you're wrapping everything you do against MySQL server inside a transaction.
Your options are:
Do not start transactions automatically by default (and do it manually whenever you actually need them)
Commit the transaction on success

Error Checking for PDO Prepared Statements [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
I'm trying to create proper error handling for queries on a MySQL database using PDO prepared statements. I want the program to exit the moment an error in the prepared statement process is detected. Taking advantage of the fact that each step in the PDO prepared statement process returns False on failure, I threw together this repugnant hack:
global $allFields;
global $db;
global $app;
//dynamically append all relevant fields to query using $allFields global
$selectQuery = 'SELECT ' . implode($allFields, ', ') .
' FROM People WHERE ' . $fieldName . ' = :value';
//prepared statement -- returns boolean false if failure running query; run success check
$success = $selectQueryResult = $db->prepare($selectQuery);
checkSuccess($success);
$success = $selectQueryResult->bindParam(':value', $fieldValue, PDO::PARAM_STR);
checkSuccess($success);
$success = $selectQueryResult->execute();
checkSuccess($success);
with checkSuccess() doing the following:
function checkSuccess($success) {
if ($success == false) {
//TODO: custom error page.
echo "Error connecting to database with this query.";
die();
}
}
Two things. First, this is horribly verbose and stupid. There must be a better way. Obviously I could store the booleans in an array or something to take out a line or 2 of code, but still.
Second, is it even necessary to check these values, or should I just check the result after I perform this line of code:
$result = $selectQueryResult->fetch(PDO::FETCH_ASSOC);
I already have code that does this:
if ($result) { //test if query generated results
// do successful shit
}
else {
echo "404";
$app->response()->status(404); //create 404 response header if no results
As much as I try to break the prepared statement process by inserting weird, mismatched, or lengthy queries, my program always makes it to the $result assignment without returning false on any of the functions where I run checkSuccess(). So maybe I don't need to be checking the above logic at all? Keep in mind that I check for a successful database connection earlier in the program.
I preffer setting the error mode to throwing exceptions like this:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
right after I connect to the database. So every problem will throw an PDOException
So your code would be:
$selectQuery = '
SELECT
' . implode($allFields, ', ') . '
FROM
People
WHERE
' . $fieldName . ' = :value
';
try
{
$selectQueryResult = $db->prepare($selectQuery);
selectQueryResult->bindParam(':value', $fieldValue);
$selectQueryResult->execute();
}
catch(PDOException $e)
{
handle_sql_errors($selectQuery, $e->getMessage());
}
where the function would be:
function handle_sql_errors($query, $error_message)
{
echo '<pre>';
echo $query;
echo '</pre>';
echo $error_message;
die;
}
In fact I am using a general function that also has something like
$debug = debug_backtrace();
echo 'Found in ' . $debug[0]['file'] . ' on line ' . $debug[0]['line'];
to tell me where was the problem if I am running multiple queries
You have to catch PDOException:
try {
//your code/query
} catch (PDOException $e) {
//Do your error handling here
$message = $e->getMessage();
}
PDOException

Using multiple database on my web page on same host

I just referenced this answer and what I preferred was very first solution, now the issue is he has given an information for mysql_() but am using mysqli_(), so using 4th parameter as true, I select the database when user logs in, the moment he logs in he gets redirected to respective page but it is showing that connection was actively refused. any Idea how I can use 2 database, 1 is my default engine database which I need to keep it on for running my framework and second database to run respective scripts according to the user logged in...
What am trying is this
<?php
$database_connect = mysqli_connect('localhost', 'root', '', 'engine');
if(!$database_connect) {
die ('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
if(isset($_SESSION['system_id'])) {
$system_database = mysqli_connect('localhost', 'root', '', $_SESSION['system_name'], true);
if(!$system_database) {
die ('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
}
?>
P.S I want a procedural way
You don't need any extra parameters, simply do it like this
<?php
$database_connect = mysqli_connect('localhost', 'root', '', 'engine');
if(!$database_connect) {
die ('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
if(isset($_SESSION['system_id'])) {
$system_database = mysqli_connect('localhost', 'root', '', $_SESSION['system_name']);
if(!$system_database) {
die ('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
}
//Now whatever query you write, just do it like this
$access = mysqli_query($database_connection_var, "/*Query Goes Here*/"); //Will get database name from $database_connection_var
$access2 = mysqli_query($database_connection_var2, "/*Query Goes Here*/"); //Will get database name from $database_connection_var2
?>

Querying a database with oop

I have connected to a database for the first time with oop and stright away come up with an issue, below is my code which i'm struggling with:
$q = 'SELECT * FROM test';
$sqli->query($q);
if($sqli->query($q)){
echo "worked";
}
if($sqli->error){
echo $sqli->error;
}
I have checked for errors when connecting to the db and that works fine, but when I run this query I get no output, why? I expected an error or "worked", but have got neither.
Whats happening?
I have put some comments in the source code to help:
$q = 'SELECT * FROM test';
//$sqli is the result of a
//new mysqli("localhost", "user", "password", "database");
$resource = $sqli->query($q); // this returns a resource or false
if(!$resource) {
echo $sqli->error;
die; // do not process further
}
// process the results
$rows = $resource->fetch_all();
if ($rows) { // check if there are rows
echo "worked";
}
else {
echo "query is ok, but there are no rows";
}
You could also use $resource->fetch_object() which returns an object for output. Therefore if you wanted to print specific data from the result set, you would do something like
//table test.Name and test.Country
while ($rowobj = $resource->fetch_object()){
printf ("%s (%s)\n", $rowobj->Name, $rowobj->Country);
}
Good luck,
You could use this method, I hope it's what you are looking for. You will need to define the DB first. Then you can connect in OOP and test the connection is true or exit();
Let me know if this works for you. You can also define the DB in an external file and just do an include(); towards the top of your script for any pages needing connection to the DB.
define("SERVER","IP Address");
define("USER","DB USERNAME");
define("PASSWORD","DB PASSWORD");
define("DATABASE","DB NAME");
// This is for connection
$mysqli = new mysqli(SERVER, USER, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit();
}

Categories