SP_HELP output to PHP array - php

I am trying to create a simple PHP page that describes the tables of my DB so I can always find a table/column name or data type that I am looking for (a sort of poor man's schema if you will).
I have done this in the past with a Sybase DB but our new DB will be SQL Server so I am trying to reproduce it using that DB.
try {
$conn = new PDO("odbc:Driver={SQL Native Client};Server=servername,1433;Database=dbname;Uid=user;Pwd=password;");
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch(PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
try {
$query = $conn->query("execute sp_help tablename");
} catch(PDOException $e) {
echo "Error: ".$e->getMessage();
}
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
print_r($result);
}
But it's as if I only get the first result (it doesn't loop). I was expecting something like the example given here SQL Server FAQ but all I get is the first row (name, owner, type, date_created) the result set does not go on to give the column names etc (which is what I'm really after).
Any ideas?
Update: According to TechNet if the argument given is a user table, it should return the columns, but in this case it does not. All I get is...
Array ( [Name] => TableName [Owner] => dbo [Type] => user table [Created_datetime] => 2013-07-15 23:26:43.377 )

The only way I can think of is create procedure on the sybase side that could call sp_help and would return require data. That procedure could be used as you need.

Related

How to print drop table result through PDO

$droptable = 'DROP TABLE cars';
$resultd = $db->prepare($droptable);
$resultd->execute();
$printresult = $resultd->fetchAll();
echo "<pre>";
print_r($printresult);
echo "</pre>";
I am trying to test something with PDO and created an execute query for the drop table query, but I could not see anything on the screen. Am I making some fundamental programming fundamental or there will be a way around?
fetchAll will not work, as there are not records generated.
$resultd->debugDumpParams(); // print to screen
/* to push the debug to a var */
ob_start();
$content = ob_get_contents();
ob_end_clean();
/* or to just get the error message */
if($resultd->execute())
echo " Table deleted ";
else
print_r($sql->errorInfo());
DROP is a DDL (Data Definition Language) statement, it can't possibly return anything.
The statement can succeed or fail. You could manually check the result of every database method call, but you're better off configuring PDO to throw exceptions on error.
It's also unnecessary to prepare the statement since there aren't parameters to bind.
Putting all this together:
$db = new \PDO($dsn, $user, $pass, [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]);
$droptable = 'DROP TABLE cars';
$db->query($droptable);
You'll get PDOException if something goes wrong or the code will just continue running otherwise. If you really expect the removal to fail now and then during normal operations, you can capture the exception as usual:
try {
$db->query($droptable);
echo 'Table dropped successfully';
} catch(\PDOException $e) {
echo 'Could not drop table: ', $e->getMessage();
}

MySQL transaction: queries committed anyway

I discovered PDO and transactions few days ago and they're great. Today I wrote my first transaction but it didn't end as expected. To test it I put a wrong inexistent table in one of the two queries and, independently of which one, the other (correct) one is committed anyway.
I read the syntax structure on some websites and it seems to be correct, but maybe the error is right there. The tables are InnoDB. Or better, phpMyAdmin, into the db overview's table, reports MyISAM on the last summary row but the column "type" of each table's row reports InnoDB; I think this could be 'cause MyISAM is the default type on the server, is that right?
Here's the code:
$conn = new PDO($db->getDsn(), $db->getUsername(), $db->getPassword());
try {
$conn->beginTransaction();
$stmt = $conn->prepare('INSERT INTO trips (country_code, year, img, showX) VALUES (:country_code, :year, :img, :showX)');
$stmt->execute(array(':country_code' => strtolower($country_code), ':year' => $year, ':img' => $rename_response, ':showX' => $show_hide));
$tripID = $conn->lastInsertId();
$stmt = $conn->prepare('INSERT INTO trips_multilang (tripID, lang, country_name) VALUES (:tripID, :lang, :country_name)');
$stmt->execute(array(':tripID' => $tripID, ':lang' => $trip_lang, ':country_name' => strtolower($country_name)));
$conn->commit();
} catch (PDOException $e) {
$conn->rollBack();
die($e->getMessage());
}
Add to your $db class another method, $db->getOptions(), that returns an array
return [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
and then call PDO as
$conn = new PDO($db->getDsn(), $db->getUsername(), $db->getPassword(), $db->getoptions());
After that your code will start to catch up.
For now you are catching exceptions for nought, as none actually thrown.
On a side note, you must catch Exception, not PDOException and also you must re-throw an exception in case of error instead of dying out.

how to find record insert to mysql using commit()

Sorry for this beginners question and i'm not a PHP developer, but now i'm trying to learn it.
i want to add record in MySQL data base and i'm using transactions lock.
my code is as below.
$SqlQuery="INSERT INTO tab_photo VALUES('$PhotoID','$ProjectId','$Day','$barCode','$photoName','$PhotoXml')";
$waiting = true;
while($waiting) {
try {
// save border data
$stmt = $conn->prepare($SqlQuery);
$conn->beginTransaction();
$stmt->execute();
sleep(1);
$x=$conn->commit();
echo "x value-".$x;
echo "Success";
$waiting = false;
}
catch (PDOException $e){
echo "Failled :".$PhotoID."-".$PhotoID;
if(stripos($e->getMessage(), 'DATABASE IS LOCKED') !== false) {
// This should be specific to SQLite, sleep for 0.25 seconds
// and try again. We do have to commit the open transaction first though
$conn->commit();
usleep(250000);
} else {
$conn->rollBack();
throw $e;
}
}
}
in here as output it gives,
x value-1 Success
but actually this record doesn't add to the database.
My Questions:
Even the commit is successful(output 1) how does it not added to the database?
how can i check whether record is added to database? ( Is there any way to find it without write select statement?
As I understand, you expect that PDOException will be thrown when statement is failed to execute. But as I can see, exception is not thrown by default in such cases.
See how you can change that here
Suppose in your case you should have a code like this:
$conn = new PDO($connection_string);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // this will force PDO to throw exception when SQL statement fails instead of simply setting an error.
Suppose this will work fine for you.
Please note that you should not use
$SqlQuery="INSERT INTO tab_photo VALUES('$PhotoID','$ProjectId','$Day','$barCode','$photoName','$PhotoXml')";
Instead of that, you should use parameters binding:
$SqlQuery="INSERT INTO tab_photo VALUES(:PhotoID,:ProjectId,:Day,:barCode,:photoName,:PhotoXml)";
$stmt = $conn->prepare($SqlQuery);
$conn->beginTransaction();
$stmt->execute(array(':PhotoID' => $PhotoID, ':ProjectId' => $ProjectId, ....));
sleep(1);
See this for more details.

Get last record in mysql

Using this php code:
try{
$dbh = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// INSERT CLEAN DATA INTO TABLEā€¦
$sth = $dbh->prepare("
INSERT INTO Fan(fanNm,fanEmail,fanPass,fanDynamSalt)
VALUES('$userName','$userEmailAddress','$userPassword','$dynamSalt')"
);
$sth->execute();
////////////////////////////////////////////////////////////////////
## Set Session Var for this PK ID in Fan table that is being created ##
////////////////////////////////////////////////////////////////////
$_SESSION['newUserSessID'] = mysql_insert_id();
echo "<strong style='color:#fff;'>".$_SESSION['newUserSessID']."</strong>";
} //try
catch(PDOException $e){
echo "Oops, We're experiencing an error.";
file_put_contents('/PDODBConnectionErrors.txt', $e->getMessage(), FILE_APPEND);
} //catch
It inserts FINE into the database, but I am using echo "<strong style='color:#fff;'>".$_SESSION['newUserSessID']."</strong>"; to echo out that value and it ALWAYS returns a zero.
Even if I run :
SELECT LAST_INSERT_ID( )
FROM Fan
LIMIT 0 , 30
It gives me output like
0
0
(since there is two rows in database table)
Anyone?
You should not use mysql_insert_id as that isn't part of PDO (which is what you're using to interact with the database in this instance).
Instead use PDO::lastInsertId():
$_SESSION['newUserSessID'] = $dbh->lastInsertId();
More info: http://www.php.net/manual/en/pdo.lastinsertid.php
You're mixing PDO with generic MySQL functions. The problem is the mysql_last_insert has no resource, and so it returns 0 for false. Don't mix PDO with generic MySQL functions.
To get the last insert id in PDO, do this:
$dbh->lastInsertId()
http://php.net/manual/en/pdo.lastinsertid.php

prepared parameterized query with PDO

New to this new and secure way of handling SQL's in PHP and MySql driven web based application, to secure the code from SQL injections. I am planning to start using mysqli with PDO. Can anyone please outline how should i get started and proceed.
Any reference to any article will also be helpful.
Thanks in advance.
To create the connection
try {
$db = new PDO("mysql:dbname=".DB_NAME.";host=".DB_HOST,DB_USER,DB_PWD);
} catch (PDOException $e) {
die("Database Connection Failed: " . $e->getMessage());
}
Then to prepare a statement
$prep = $db->prepare("SELECT * FROM `users` WHERE userid = ':id'");
As you can see, you label each parameter you'd like by prefixing any string with ':'. Then all you do is pass an array mapping the parameter (:id) to the value when you execute.
if (!$prep->execute(array(":id" => $userinput))) {
$error = $prep->errorInfo();
echo "Error: {$error[2]}"; // element 2 has the string text of the error
} else {
while ($row = $prep->fetch(PDO::FETCH_ASSOC)) { // check the documentation for the other options here
// do stuff, $row is an associative array, the keys are the field names
}
}
Instead of PDO::FETCH_ASSOC with the "fetch" function, there are various other ways to get your data. You can use fetchAll to get an array of ALL the results at once instead of just going row by row. Or you can get the array of information as a 0-indexed array, or you can even fetch the results directly into a class instance (if the field names line up with the properties of the class.)
All the documentation of PDO can be found here: PHP.net PDO Manual

Categories