how can insert admin user fields in database when install script php - php

i start write a script with php , for installation stage i face to a problem.
when i install sql table with php code and after that "in same code page" i want insert admin_user information to user table , without any error user information not inserted in database but when i install Manually database table and after that run same code for insert admin_user information inserted run good and information inserted in database.
My Query Run PDO Method :
// Execute query
public function Tbmedia_runquery($query_body = "" , $parameter_array ="" ){
$query = $query_body;
$stmt = $this->Tbmedia_connection->prepare($query);
if(is_array($parameter_array)){
// declare bind_param variable
foreach ($parameter_array as $key => &$value) {
$stmt->bindParam(":$key",$value);
//':$key'
}
}
$stmt->execute();
$stmt->closeCursor();
return $stmt;
}
And this is My Create Database Table Function :
//Create DB Table
function Tbmedia_dbcreator($db_con){
$dir_sql = __DIR__."/../../install/tbmedia.sql";
if(!file_exists($dir_sql) or is_writable($dir_sql)){
$line_array = file($dir_sql);
$query_line = "";
$query = "";
foreach ($line_array as $value) {
if(substr($value,0,2) == "--")
continue;
$query_line .=$value;
if (substr(trim($value),-1,1) == ";"){
try{
$query = $db_con->Tbmedia_runquery($query_line);
$query_line = "";
}catch (Exception $e){
$file_name = basename($e->getFile());
$file_line = $e->getLine();
Tbmedia_die();
}
}
}
}else{
Tbmedia_die();
}
}
And this is simple insert sql for insert user user information after run function Tbmedia_dbcreator() :
$db_con->Tbmedia_runquery('INSERT INTO `tbmedia`.`tbmedia_user` (`user_name`,`user_state`) VALUE ("FARAMARz",1)');
Why this is happening ? can't create table and insert data to it in one page code ?

Related

Move MySQL table row to another table using PDO

i tried to follow this mysql - move rows from one table to another with action to perform a "move to archive" function using PDO and i am failing miserably.
So i have created a job card system, and to cut it short, when a job is complete, i have a "ARCHIVE" button that essentially needs to move the selected job card from table "repairs" into table "archived_repairs". The 2 tables are exactly the same, it just needs to be deleted from repairs table and moved to archived_repairs table in case we need to come back to it at a later stage.
This is the button/link i am using on my CRUD table:
<td>Archive</td>
The above is fine and dandy and goes to a page i named "archive_repair.php" with the following php code:
<?php
require_once "connection.php";
if (isset($_REQUEST['archive_id']))
{
try
{
$job_number = $_REQUEST['archive_id'];
$select_stmt = $db->prepare('SELECT * FROM repairs WHERE job_number =:job_number');
$select_stmt->bindParam(':job_number', $job_number);
$select_stmt->execute();
$row = $select_stmt->fetch(PDO::FETCH_ASSOC);
extract($row);
}
catch(PDOException $e)
{
$e->getMessage();
}
}
if (isset($_REQUEST['btn_archive']))
{
$job_number = $_REQUEST['job_number'];
$date = $_REQUEST['date'];
$client_full_name = $_REQUEST['client_full_name'];
$client_email = $_REQUEST['client_email'];
$client_phone = $_REQUEST['client_phone'];
$item_for_repair = $_REQUEST['item_for_repair'];
$repair_description = $_REQUEST['repair_description'];
$hardware_details = $_REQUEST['hardware_details'];
$diagnostic_fee = $_REQUEST['diagnostic_fee'];
$tech_assigned = $_REQUEST['tech_assigned'];
$current_status = $_REQUEST['current_status'];
$technician_notes = $_REQUEST['technician_notes'];
$admin_notes = $_REQUEST['admin_notes'];
$invoice_status = $_REQUEST['invoice_status'];
$invoice_number = $_REQUEST['invoice_number'];
if (empty($invoice_status))
{
$errorMsg = "Please change Invoice Status Before Archiving this Job Card";
}
else if (empty($invoice_number))
{
$errorMsg = "Please Enter a SAGE Invoice Reference Before Archiving this Job Card";
}
else
{
try
{
if (!isset($errorMsg))
{
$archive_stmt = $db->prepare('INSERT INTO archived_repairs job_number=:job_number, date=:date, client_full_name=:client_full_name, client_email=:client_email, client_phone=:client_phone, item_for_repair=:item_for_repair, repair_description=:repair_description, hardware_details=:hardware_details, diagnostic_fee=:diagnostic_fee, tech_assigned=:tech_assigned, current_status=:current_status, technician_notes=:technician_notes, admin_notes=:admin_notes, invoice_status=:invoice_status, invoice_number=:invoice_number');
$archive_stmt->bindParam(':job_number', $job_number);
$archive_stmt->bindParam(':date', $date);
$archive_stmt->bindParam(':client_full_name', $client_full_name);
$archive_stmt->bindParam(':client_email', $client_email);
$archive_stmt->bindParam(':client_phone', $client_phone);
$archive_stmt->bindParam(':item_for_repair', $item_for_repair);
$archive_stmt->bindParam(':repair_description', $repair_description);
$archive_stmt->bindParam(':hardware_details', $hardware_details);
$archive_stmt->bindParam(':diagnostic_fee', $diagnostic_fee);
$archive_stmt->bindParam(':tech_assigned', $tech_assigned);
$archive_stmt->bindParam(':current_status', $current_status);
$archive_stmt->bindParam(':technician_notes', $technician_notes);
$archive_stmt->bindParam(':admin_notes', $admin_notes);
$archive_stmt->bindParam(':invoice_status', $invoice_status);
$archive_stmt->bindParam(':invoice_number', $invoice_number);
if ($archive_stmt->execute())
{
$delete_stmt = $db->prepare('DELETE FROM repairs WHERE job_number =:job_number');
$delete_stmt->bindParam(':job_number', $job_number);
$delete_stmt->execute();
header("refresh:1;repairs.php");
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
?>
This is my connection.php file:
<?php
$db_host="localhost"; //localhost server
$db_user="ecemscoz_ecemsapp"; //database username
$db_password="C3m3t3ry!#"; //database password
$db_name="ecemscoz_ecemsapp"; //database name
try
{
$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
$e->getMessage();
}
?>
When i click on the ARCHIVE button/link, the page is just blank (white screen), no errors show, nothing is moved to the other database and nothing is deleted. Ive only been coding PHP since 2020 so still new at this, but from my understanding this should of worked... Am i missing something in my code that i am not seeing?
You'll have a much easier time doing this directly in MySQL.
Something like the following should be essentially all you need.
$archive_stmt = $db->prepare("INSERT INTO archived_repairs (
job_number,
date,
client_full_name,
client_email,
client_phone,
item_for_repair,
repair_description,
hardware_details,
diagnostic_fee,
tech_assigned,
current_status,
technician_notes,
admin_notes,
invoice_status,
invoice_number
) (
SELECT
job_number,
date,
client_full_name,
client_email,
client_phone,
item_for_repair,
repair_description,
hardware_details,
diagnostic_fee,
tech_assigned,
current_status,
technician_notes,
admin_notes,
invoice_status,
invoice_number
FROM
repairs
WHERE
job_number =:job_number )");
$archive_stmt->bindParam(':job_number', $job_number);
if ($archive_stmt->execute())
{
$delete_stmt = $db->prepare('DELETE FROM repairs WHERE job_number =:job_number');
$delete_stmt->bindParam(':job_number', $job_number);
$delete_stmt->execute();
header("refresh:1;repairs.php");
}

Unable to update values to database in PHP and MySQL

I am trying to update the value to database, but one way or an another i am not able to.
Code:
<?php
include 'init.php';
$dataid = $_POST['data_id'];
if(isset($dataid))
{
/*user connects to database and performs some operation here*/
/* values from database is returned and user passes the same to below function */
calculateamount($kk_data_id,$kk_egg,$kk_cash,$kk_in,$kk_out,$kk_expenditure,$kk_cashout,$kk_wholesale1,$kk_wholesale2,$kk_wholesale3,$kk_touch,$kk_galtha,$kk_kotla,$wholesale_1,$wholesale_2,$wholesale_3,$touch,$galtha,$kotla,$retail,$prevegg,$prevcash);
}
function calculateamount($kk_data_id,$kk_egg,$kk_cash,$kk_in,$kk_out,$kk_expenditure,$kk_cashout,$kk_wholesale1,$kk_wholesale2,$kk_wholesale3,$kk_touch,$kk_galtha,$kk_kotla,$rwholesale_1,$rwholesale_2,$rwholesale_3,$rtouch,$rgaltha,$rkotla,$rretail,,$prevegg,$prevcash)
{
/*performs Mathematical operations
with data retrieved and passes the final values to the below function to update to database*/
//ALL THE VALUES ARE CONVERTED TO STRING BEFORE PASSING ON TO THE BELOW FUNCTION
updatevaluestodatabase($finalwhl1amount,$finalwhl2amount,$finalwhl3amount,$finaltchamount,$finalgalamount,$finalkotamount,$finalretailval,$finalretamount,$finaltotamount,
$finaltottally);
}
function updatevaluestodatabase($finalwhl1amount,$finalwhl2amount,$finalwhl3amount,$finaltchamount,$finalgalamount,$finalkotamount,$finalretailval,$finalretamount,$finaltotamount,
$finaltottally)
{
$updatedata = "UPDATE kk_data SET wholesale1_amt=?,wholesale2_amt=?,wholesale3_amt=?,touch_amt=?,galtha_amt=?,kotla_amt=?,
kk_retail=?,retail_amt=?,kk_total_amount=?,kk_final_tally=? where kk_data_id = ?";
$updatestmt = mysqli_prepare($con, $updatedata);
mysqli_stmt_bind_param($updatestmt, sssssssssss,$finalwhl1amount,$finalwhl2amount,$finalwhl3amount,$finaltchamount,$finalgalamount,$finalkotamount,$finalretailval,$finalretamount,
$finaltotamount,$finaltottally,$dataid);
mysqli_stmt_execute($updatestmt);
mysqli_stmt_store_result($updatestmt);
$response = array();
$response["success"] = false;
if(mysqli_stmt_affected_rows($updatestmt) > 0 )
{
$response["success"] = true;
}
header('Content-Type: application/json');
echo json_encode($response);
}
?>
OUTPUT
Every time I run the below script in postman ('data_id' = value) or through application:
$response["success"] = false;
is returned always . Data is not updated to the database.
What I tried
Instead of using mysqli_stmt_affected_rows($updatestmt) I tried executing using mysqli_stmt_execute($updatestmt); in the if statement. But no luck there
I am unable to figure out where the issue is or if am incorrect in calling the function.
NOTE: I thought I would post a minimized code to avoid clumsiness.

SELECT COUNT * SQL PHP doesn't work

I have to search if a postal code is in my database, my table is called "test" there is only one table in my database with one column and one row, the column is named "codes", and there is an only row with the INT 63000, i have a form in my website where client enter a code, and it called a .php file which check if the value is missing or present in the database, i don't know PHP so it's hard for me... :( And my code don't work :(
SOLVED : THIS IS THE WORKING CODE :
<?php session_start(); ?>
<?php
if($_POST['code-postal'] === '') {
$hasError = true;
} else {
$variable = $_POST['code-postal'];
$code = intval($variable);
}
mysql_connect('xxxxxxxxx', 'xxxxxxxxxxxx', 'xxxxxxxxxxxx')
or die("I cannot connect to the database because: " . mysql_error());
mysql_select_db('xxxxxxxxxx');
$code = mysql_real_escape_string($code);
$sql = "SELECT COUNT(*) AS total_count FROM test WHERE codes='$code'";
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
$data = mysql_fetch_assoc($req);
if($data['total_count'] == 1) {
$verif = true;
}
else {
$verif = false;
}
// on ferme la connexion à mysql
mysql_close();
?>
$sql = "SELECT COUNT(*) AS total_count FROM test WHERE codes='$code'";
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
$data = mysql_fetch_assoc($req);
if($data['total_count'] == 1) {
$verif = true;
}
else {
$verif = false;
}
Here is the working code.
mysql_query would return result set. You will need to use mysql_fetch_assoc function to retrieve data from that.
I guess you would have more rows in table in future, because as you mentioned in table that you have only one table with one column and one row, then there is no need of database, you can directly compare values.

How to make echo results in table hyperlinks

I have retrieved data from DB and inserted into a html table however I want to make each value in the table a hyperlink to another page. Below I have tried making the pupil_id and link to a profile.php but all pupil_id values have now vanished!
(if (!isset($_POST['search'])) {
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0) {
$totalpupil = "There are currently no Pupils in the system.";
} else {
while ($row = mysql_fetch_array($pupils)) {
?>
<tr>
<td><?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?></td>
<td><?php echo $row['pupil_name'] ?></td>
<td><?php echo $row['class_id'] ?></td>
</tr>
<?php
}
}
})
The finishing table should display every hyperlink as a hyperlink to another page. Any help?
Because your HTML is invalid, you are missing a closing > and you have no text defined for the hyperlink
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?> //Wrong
Correct would be
<?php echo ''.$row['pupil_id'].''; ?>
Try replace this:
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?>
with this:
<?php echo "<a href='profile.php?id=".$row['pupil_id']."'>link</a>"; ?>
Also, you dont have <table> tags at all.
You don't put any text between your link tags, text here
Maybe this will help you:
<td><?php echo ''.$row['pupil_name'].'' ?></td>
http://uk3.php.net/mysql_query
Watch out, which ever resource you are learning from may well be quite old. mysql_query is now deprecated.
http://uk3.php.net/manual/en/ref.pdo-mysql.php is a replacement.
Here is a kick starter to using PDO (this is much much safer) i write a while ago.
Include this file in which ever php script needs to access your db. An example file name would be 'database.php' but that is your call. Set the namespace from 'yourproject' to whatever your project is called. Correct the database credentials to suit your database
This will save you a lot of headaches hopefully!
I have given some example uses at the bottom for you. I remember when i started out getting clear advice was sometimes hard to come by.
//***** in a database class file*****/
namespace yourproject;
class Database {
private $db_con = '';
/*** Function to login to the database ***/
public function db_login()
{
// Try to connect
try{
// YOUR LOGIN DETAILS:
$db_hostname = 'localhost';
$db_database = 'yourdatabasename';
$db_username = 'yourdatabaseusername';
$db_password = 'yourdatabasepassword';
// Connect to the server and select database
$this->db_con = new \PDO("mysql:host=$db_hostname;dbname=$db_database",
"$db_username",
"$db_password",
array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// Prevent emulation of prepared statements for security
$this->db_con->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
$this->db_con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return true;
}
// If it fails, send user to maintenance page
catch(PDOException $e)
{
header("location:http://yourwebsiteurl.com/maintenance.php");
exit();
}
}
/*** Function for database control ***/
public function db_control($query , $parameters, $returnID = false)
{
if(!is_array($query) && is_array($parameters))
{
try{
//prepare the statement
$statement = $this->db_con->prepare($query);
//execute the statement
$statement->execute($parameters);
//check whether this is a select, if it is then we need to retrieve the selected data
if(strpos($query, 'SELECT') !== false)
{
//fetch the results
$result = array();
while( $row = $statement->fetch(\PDO::FETCH_ASSOC) )
{
$result[] = $row;
}
//count the results
$count = count($result);
//return the array
return array( 'results' => $result, 'result_count' => $count );
}
//else return the number of affected rows
else{
//count the affected rows and place into a returnable array
$affected_rows = $statement->rowCount();
$returnArray = array('result_count' => $affected_rows);
//check to see if we are to return a newly inserted autoincrement ID from an INSERT
if($returnID)
{
//find the newly created ID and add this data to the return array
$insertID = $this->db_con->lastInsertId();
$returnArray['ID'] = $insertID;
}
return $returnArray;
}
}
catch(PDOException $e)
{
return false;
}
}
else{
return false;
}
}
}
// Start the database class and connect to the database then create a globally accessible function for ease of reference
$db = new \yourproject\Database();
$db->db_login();
function _db( $sql , $params , $returnID = false ){
return $GLOBALS['db']->db_control( $sql , $params , $returnID );
}
When you include this file you now have a new function: _db(). As the function is global it can be called from within any class or std file. When called into a variable as demonstrated below will result in an array like this:
array(
'result_count' => 3,
'results' => array(
array(/*row 1*/),
array(/*row 2*/),
array(/*row 3*/),
.. etc etc
)
)
Now include your database file in your php script:
//call in the database file
require_once 'database.php';
//your query as in the op
$sql = 'SELECT * FROM pupil';
//your params for the query
$params = array();
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//if no results
if( $query['result_count'] == 0 )
{
echo 'sorry no pupils in the system';
}
else
{
//looping through each result and printing into a html table row
for( $i = 0 ; $i < $query['result_count'] ; ++$i )
{
echo '<tr><td><a href="profile.php?id=' . $query['results'][$i]['pupil_id'] . '"</a></td>';
echo '<td>'. $query['results'][$i]['pupil_name'] . '</td>';
echo '<td>'. $query['results'][$i]['class_id'] . '</td></tr>';
}
}
Your original query but with some parameters passed through
//Passing parameters to the query
//your query
$sql = 'SELECT * FROM pupil WHERE pupil_id = :pupil_id AND class_id = :class_id';
//your params for the query
$params = array(
':pupil_id' => 12,
':class_id' => 17,
);
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//deal with the results as normal...
If you set the 3rd param as true you can return the automatic id of the row just entered eg:
//where $sql is a query that will INSERT a row
$query = _db($sql,$params, true);

How do I use Interbase transactions with PHP?

I have a PHP site connected to an Interbase DB. The DB contains orders which users can load and are displayed on screen. The user can make changes to the order and save them. This works but if 2 users load and save the same record then the order contains the changes made by the last user who saved.
When the 2nd user tries to save I want a message to pop up saying the order has been changed and stop the order from being saved.
I know that interbase has transactions to do this as I have a desktop app that implements transactions and the above scenario. However, I do not know how to do the same thing with PHP in a web environment.
The desktop app keeps the db open all the time and the transaction is kept alive from the time it was read to committed. With PHP the db and transaction is opened/created only when each query is run. From what I read the transaction is rolled back at the end of the script if it's not committed.
Code loading an order
PHP Code:
public function GetOrderDetails($in_OrderID)
{
$qry = "SELECT ID, ... , FROM CUSTOMER_INVOICE WHERE ID = $in_OrderID";
$this->dbconn = ibase_connect ($this->host, $this->username, $this->password);
$this->dbtrans = ibase_trans( IBASE_DEFAULT,$this->dbconn );
$result = ibase_query ($this->dbtrans, $qry);
while( $row = ibase_fetch_row($qryResult) )
{
}
ibase_free_result($in_FreeQry);
ibase_close($this->dbconn);
}
Code saving order
PHP Code:
public function SaveOrderDetails()
{
$DoCommit = false;
try
{
$this->dbconn = ibase_connect ($this->host, $this->username, $this->password);
$this->dbtrans = ibase_trans( IBASE_DEFAULT,$this->dbconn );
// Insert/Update the order
if( $this->UpdateOrder() )
{
// Insert Order Items
if( $this->InsertOrderItems() )
{
$DoCommit = true;
}
else
{
$this->ErrorMsg = "ERROR 0003: Order Items could not be inserted";
}
}
else
{
$this->ErrorMsg = "ERROR 0002: Order could not be inserted/updated";
}
if( $DoCommit )
{
if( ibase_commit($this->dbtrans) )
{
$OrderResult = true;
}
else
{
ibase_rollback($this->dbtrans);
$this->ErrorMsg = "ERROR 0004: DB Qry Commit Error";
print $this->ErrorMsg ;
}
}
else
{
ibase_rollback($this->dbtrans);
}
}
catch( Exception $e )
{
ibase_rollback($this->dbtrans);
$this->ErrorMsg = "ERROR 0001: DB Exception: " . $e;
}
ibase_close($this->dbconn);
}
If anyone can tell me where I'm going wrong that would be great. Or, if no one uses Interbase how would you do it with MySQL? I don't want to go down the table locking, timestamp route.
Thanks
Ray
you must use primary key to avoid it. u can use generator to get unique id for each order.

Categories