Insert data into multiple table using PHP - php

I am trying to add data into 2 tables using PHP
My PHP code: insert.php
<?php
session_start();
$db['host'] = "dbhost";
$db['user'] = "user";
$db['pass'] = "pass";
$db['name'] = "dbname";
//making an array with the data recieved
$data = array('f_name' => $_POST['txt_f_name'],
'l_name' => $_POST['txt_l_name'],
'VNum' => $_POST['txtVisaNo']);
try {
// preparing database handle $dbh
$dbh = new PDO("mysql:host=".$db['host']."; dbname=".$db['name']."", $db['user'], $db['pass']);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insertall = "BEGIN; "
. "INSERT INTO students (f_name, l_name) "
. "VALUES (:f_name, :l_name); "
. "INSERT INTO visa (students_id, VNum) "
. "VALUES (:LAST_INSERT_ID(), :VNum); "
. "$addStdInf->execute($data); "
. "COMMIT;";
$addStdInf = $dbh->prepare($insertall);
echo 'Success!';
}
catch(PDOException $e){
echo $sql,'<br />', $e->getMessage();
}
$dbh = null;
?>
Notice is "Success!" but it inserted nothing into database, please guide me the ERROR.Thank you.

You are only preparing the statement - you never execute it. After the prepare call you receive a ready to execute statement, if you execute it with some parameters, it will be inserted in the database:
http://php.net/manual/en/pdostatement.execute.php

You are forget to execute your pdo statements
<?php
session_start();
$db['host'] = "dbhost";
$db['user'] = "user";
$db['pass'] = "pass";
$db['name'] = "dbname";
//making an array with the data recieved
$data = array('f_name' => $_POST['txt_f_name'],
'l_name' => $_POST['txt_l_name'],
'VNum' => $_POST['txtVisaNo']);
try {
// preparing database handle $dbh
$dbh = new PDO("mysql:host=".$db['host']."; dbname=".$db['name']."", $db['user'], $db['pass']);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insertall = "BEGIN; "
. "INSERT INTO students (f_name, l_name) "
. "VALUES (:f_name, :l_name); "
. "INSERT INTO visa (students_id, VNum) "
. "VALUES (:LAST_INSERT_ID(), :VNum); "
. "$addStdInf->execute($data); "
. "COMMIT;";
$addStdInf = $dbh->prepare($insertall);
$result = $addStdInf->execute();
if ($result) {
echo 'Success!';
} else {
echo 'please check';
}
}
catch(PDOException $e){
echo $sql,'<br />', $e->getMessage();
}
$dbh = null;
?>

Related

PHP executes sql inside a false condition of IF statement with $_POST

Please help with this difficult to understand bug: php always execute sql update inside IF with $_POST in condition.
When condition is false: the code i) not executes the echo command, but ii) it still executes the sql command
if ($_POST["scanned_set"] != "saved") {
try {
$conn = new PDO("mysql:host=$servername;dbname=abc", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update
$sql = "UPDATE `id_scan` SET `scan_count` = 10 WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
and the strange thing is that, if I try the iF condition with "IF (1 ==2)" then code works well. In other words, it does not execute the sql.
The full code
<html>
<body>
<?php
$servername = "localhost";
$username = "reviinve_vchain";
$password = "";
var_dump($_POST["scanned_set"]);
try {
$conn = new PDO("mysql:host=$servername;dbname=reviinve_vchain", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Retrieve data from db
$sql = "SELECT * FROM `id_scan` WHERE `id` = 1";
foreach ($conn->query($sql) as $row) {
echo "print scan number after retrieving statement ".$row['scan_count'] . "\t";
// print $row['color'] . "\t";
$count_update = $row['scan_count'] + 1;
}
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
if ($_POST["scanned_set"] != "saved") {
try {
$conn = new PDO("mysql:host=$servername;dbname=reviinve_vchain", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update count number to db
echo 'new count number' . $count_update;
$sql = "UPDATE `id_scan` SET `scan_count` = $count_update WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
?>
</body>
</html>
Try scrubbing your request variable first:
$do_update = !(trim(strtolower($_REQUEST["scanned_set"])) == "saved")
if ($do_update) {
try {
$conn = new PDO("mysql:host=$servername;dbname=abc", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update
$sql = "UPDATE `id_scan` SET `scan_count` = 10 WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}

Why does my PDO $stmt->bind_result() function call hang after executing a SELECT query?

I have a MySQL database with table "Test" that has one column "TestData". There are three records with the following values for TestData: "This is value 1", "Here is another string", and
"Third just for luck".
I wrote the following PHP code to retrieve the records.
<?php
try {
$hostname = "redacted";
$username = "redacted";
$password = "redacted";
$database = "redacted";
$conn = new PDO("mysql: host=$hostname; dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT TestData FROM Test";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
catch(PDOException $e)
{
$finalResult = $finalResult . "," . $e->getMessage();
}
echo "you are here (" . $stmt->rowCount() . ")<br>";
if ($stmt->rowCount() > 0) {
echo "found (" . $stmt->rowCount() . ")<br>";
$stmt->bind_result($td);
echo "bind successful<br>";
while ($stmt->fetch()) {
echo "testdata (" . $td . ")<br>";
}
} else {
echo "nothing found<br>";
}
?>
The result I receive is
you are here (3)
found (3)
The PHP script never gets to the "echo 'bind successful'" statement. The "$stmt->bind_result($td);" statement hangs.
The query appears to work, given that rowCount = 3. I've used essentially the same structure to perform INSERTS that work properly.
What's wrong with what I'm doing? Thanks.
I changed my code to the following and it works.
<?php
$hostname = "redacted";
$username = "redacted";
$password = "redacted";
$database = "redacted";
$conn = new mysqli($hostname, $username, $password, $database);
if ($conn->connect_error) {
fwrite(STDERR, "Connection failed: " . $conn->connect_error . "\n");
exit(1);
}
$sql = "SELECT TestData FROM Test WHERE ?";
$stmt = $conn->stmt_init();
if(!$stmt->prepare($sql)) {
print "Failed to prepare statement\n";
} else {
$stmt->bind_param("s", $condition);
}
$condition = "1 = 1";
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
foreach ($row as $r) {
echo "testdata(" . $r . ")<br>";
}
}
?>
No more mixing PDO and MySQLi for me. Thanks for the help. Sorry for the inconvenience.
If you are just trying to get the items from the database using php pdo you need to store the results.
$results = $stmt->fetch(); //will get one row
$results = $stmt->fetchAll(); //will take all results and store in an array
hope this helps.

Failed to select data from PHPMyAdmin using PHP PDO

This is my code:
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
?>
But, when I run it, nothing gets printed. What's wrong?
Yes, my table is not empty. I am 100% able select & print data using MySQLi Object-oriented, but not working with PDO. What's wrong in my code?
Call the function
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
//call the function here
printResult($conn);
?>
To run a function you must call it.
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
// and if this fails there is no point continuing so add an exit
exit;
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
printResult($conn); // call the function
?>
You don't call function printResult from anywhere.
Add to your code printResult($conn);

PHP read xml blob from mysql

I have stored an xml file in mySQL using the code below. I know the DB calls are not parameterized (this will be an non-public tool and will not live on the web). The create_table function also appears below and the XML file after applying addslashes is written to mySQL as MEDIUMBLOB type. The challenge is that after searching here and on the web have not been able to find means to successfully read the BLOB object from the database and display the XML. Note the last block of code where I am able to successfuly read the mySQL record and can see the XML using var_dump (700+ characters) but when I use a simple echo I only see a very small string. Thanks for the assistance!
//Creates Table for per each XML file name encountered
create_table($servername,$username,$password,$dbname,$tablename,$adminname);
//Read the contents of the XML file and write it to the table - $tablename
$xmlContent = addslashes(file_get_contents($pathName));
//$xmlContent = "test";
//Write to the table
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO $tablename (stig_release_id, stig_xml_data, admin_name,stig_xml_filename)
VALUES ($releaseID, $xmlContent, $adminname, )";
//stig_xml_filename
$sql = "insert into `".$tablename."` (`stig_release_id`,`stig_xml_data`,`admin_name`, `stig_xml_filename`) values ('".$releaseID."','".$xmlContent."','".$adminname."','".$aFileName."')";
$conn->exec($sql);
echo "<br>... New record created successfully in $tablename ";
}
catch(PDOException $e)
{
echo "<br style='color:red'>" . $sql . "<br>" . $e->getMessage();
}
$conn = null;
$xmlCount ++;
}
}
function create_table($servername,$username, $password,$dbname,$tablename,$adminname){
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE TABLE IF NOT EXISTS $tablename (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
stig_release_id VARCHAR(100) NOT NULL,
stig_xml_filename VARCHAR(200) NOT NULL,
stig_xml_data MEDIUMBLOB NOT NULL,
admin_name VARCHAR(50),
reg_date TIMESTAMP
)";
$conn->exec($sql);
echo "<br><b>Table $tablename created successfully</b>";
}
catch(PDOException $e)
{
echo $sql . "<br style='color:red'>" . $e->getMessage() . "<br>";
}
$conn = null;
}
This is a snapshot of phpAdmin showing the data in one of the tables:
Database snapshot
//Creates Table for per each XML file name encountered
create_table($servername,$username,$password,$dbname,$tablename,$adminname);
//Read the contents of the XML file and write it to the table - $tablename
$xmlContent = addslashes(file_get_contents($pathName));
//$xmlContent = "test";
//Write to the table
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO $tablename (stig_release_id, stig_xml_data, admin_name,stig_xml_filename)
VALUES ($releaseID, $xmlContent, $adminname, )";//this sql string errors out
//stig_xml_filename
$sql = "insert into `".$tablename."` (`stig_release_id`,`stig_xml_data`,`admin_name`, `stig_xml_filename`) values ('".$releaseID."','".$xmlContent."','".$adminname."','".$aFileName."')";
$conn->exec($sql);
echo "<br>... New record created successfully in $tablename ";
}
catch(PDOException $e)
{
echo "<br style='color:red'>" . $sql . "<br>" . $e->getMessage();
}
$conn = null;
$xmlCount ++;
}
}
function create_table($servername,$username, $password,$dbname,$tablename,$adminname){
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE TABLE IF NOT EXISTS $tablename (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
stig_release_id VARCHAR(100) NOT NULL,
stig_xml_filename VARCHAR(200) NOT NULL,
stig_xml_data MEDIUMBLOB NOT NULL,
admin_name VARCHAR(50),
reg_date TIMESTAMP
)";
$conn->exec($sql);
echo "<br><b>Table $tablename created successfully</b>";
}
catch(PDOException $e)
{
echo $sql . "<br style='color:red'>" . $e->getMessage() . "<br>";
}
$conn = null;
}
//Creates Table for per each XML file name encountered
create_table($servername,$username,$password,$dbname,$tablename,$adminname);
//Read the contents of the XML file and write it to the table - $tablename
$xmlContent = addslashes(file_get_contents($pathName));
//$xmlContent = "test";
//Write to the table
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO $tablename (stig_release_id, stig_xml_data, admin_name,stig_xml_filename)
VALUES ($releaseID, $xmlContent, $adminname, )";
//stig_xml_filename
$sql = "insert into `".$tablename."` (`stig_release_id`,`stig_xml_data`,`admin_name`, `stig_xml_filename`) values ('".$releaseID."','".$xmlContent."','".$adminname."','".$aFileName."')";
$conn->exec($sql);
echo "<br>... New record created successfully in $tablename ";
}
catch(PDOException $e)
{
echo "<br style='color:red'>" . $sql . "<br>" . $e->getMessage();
}
$conn = null;
$xmlCount ++;
}
}
function create_table($servername,$username, $password,$dbname,$tablename,$adminname){
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE TABLE IF NOT EXISTS $tablename (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
stig_release_id VARCHAR(100) NOT NULL,
stig_xml_filename VARCHAR(200) NOT NULL,
stig_xml_data MEDIUMBLOB NOT NULL,
admin_name VARCHAR(50),
reg_date TIMESTAMP
)";
$conn->exec($sql);
echo "<br><b>Table $tablename created successfully</b>";
}
catch(PDOException $e)
{
echo $sql . "<br style='color:red'>" . $e->getMessage() . "<br>";
}
$conn = null;
}
This is the code where I have attempted to display the data and the output below. What is strange is that when I do and array var_dump I can see the XML and able to read the other fields successfully. However, I am unable to retrieve only one short string vs. the entire XML content. Your help is greatly appreciated.
//Get XML Data from DB Test
$servername = "localhost";
$dbname = "stig_compliance";
$username = "root";
$password = "";
$tablename = "uwindows2003dcv6r40stigscap11benchmarkcpedictionary";
$fieldname = "stig_xml_data";
$user = "root";
$pass = "";
$db = $dbname;
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT stig_xml_data FROM $tablename WHERE id=1";
$sql = "SELECT * FROM $tablename WHERE id=1";
echo "<br>SQL = $sql";
if (!$result = $conn->query($sql)) {
echo "Error: Query failed to execute: \n";
echo "Query: " . $sql . "<p>";
echo "Errno: " . $conn->errno . "<p>";
echo "Error: " . $conn->error . "<p>";
return "Error: " . $conn->error;
exit;
} else {
echo "<p>Query Successfully Completed: <p>";
}
$fetchAll = mysqli_fetch_all($result,MYSQLI_ASSOC);
var_dump ($fetchAll);
$stigfilename = $fetchAll[0]['stig_xml_filename'];
$xmlstring = stripslashes($fetchAll[0]['stig_xml_data']);
echo "<br>STIG File Name = $stigfilename<br>";
echo "<br>STIG XML Data = $xmlstring<br>";
echo "<br> Try using SimpleXMLElement";
$xml = new SimpleXMLElement($xmlstring);
foreach ($xml->stig as $record) {
echo "<br>STIG Record Data: $record";
echo '<div class="STIG_record">'."\n";
echo '<p>'.$record->stig_xml_data.'</p>';
echo '<p>'.$record->stig_xml_filename.'</p>';
echo '</div><!--end STIG record-->'."\n";
}
Output for code, above

sent last id inserted variable to another page in php [duplicate]

This question already has answers here:
How to get last inserted inserted row id from PDO
(2 answers)
Closed 5 years ago.
in this code i have to insert some value in DB, then i have to take last id inserted in DB and sent it to another page to show the value of that id row. here is my code for insert data in DB :
try {
$con = new PDO("mysql:host=localhost;dbname=resume", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql_basic = "INSERT INTO user_basic_info (first_name,last_name,address,profile_pic,resume_file)
VALUES ('$FirstName','$LastName','$Address','$pic_destination','$resume_destination')";
$con->exec($sql_basic);
$last_id = $con->$lastInsertId();
} catch (PDOException $e) {
echo $sql_basic . "<br>" . $e->getMessage() . "<br>";
}
$con = null;
header('Location: DB-Read.php?id=' . $last_id);
in another php page i have to take $last_id and use it. here is my code:
try {
$user_id = $id;
$conn = new PDO("mysql:host=localhost;dbname=resume", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT first_name FROM user_basic_info where user_id = ".$user_id);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
echo "this is username: " . $result;
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
header('Location: show-edit.php?id=' . $last_id);
first of all $lastInsertId() not working !!
after that, is my way true to take $last_id from first page ?
lastInsertId is a method of the PDO object. You need to call $conn->lastInsertId();.
Your given syntax $conn->$lastInsertId(); is valid, however, it does not do, what you are expecting. It considers $lastInsertId to be a variable containing the method name to be called. The following example would work as well:
$method_name = 'lastInsertId';
$conn->$method_name();
Be aware that your solution enables anyone to fetch any row of your table. Consider using sessions.
TRY THIS:
use session:
try {
$con = new PDO("mysql:host=localhost;dbname=resume", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql_basic = "INSERT INTO user_basic_info (first_name,last_name,address,profile_pic,resume_file)
VALUES ('$FirstName','$LastName','$Address','$pic_destination','$resume_destination')";
$con->exec($sql_basic);
$_SESSION['id'] = $con->lastInsertId(); //it's a method
} catch (PDOException $e) {
echo $sql_basic . "<br>" . $e->getMessage() . "<br>";
$con = null;
header('Location: DB-Read.php?id=' . $last_id);
Now use this code
try {
$user_id = $_SESSION['id'];
$conn = new PDO("mysql:host=localhost;dbname=resume", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT first_name FROM user_basic_info where user_id = ".$user_id);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
echo "this is username: " . $result;
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
header('Location: show-edit.php?id=' . $last_id);

Categories