Is it possible to update the database and then fetch a new recordset right after that will have all this new data entered? Do I need some kind of closure to make sure the insert sql has completed before doing a new SELECT that will contain all the new records?
Ie, put simply, if I have 50 000 entries in total with a structure like this:
$sql = "INSERT INTO `acc_change`(`ID`, `type`, `name`, `amount`, `date`, `processed`)
VALUES (NULL, 'auto', 'Lorem', '75.00', '2018-04-05 00:00:00', 'no'),
(NULL, 'auto', 'Ipsum', '12.00', '2018-04-25 00:00:00', 'no'),(NULL, 'auto', 'Dolor', '24.00', '2018-04-28 00:00:00', 'no')...
INSERT INTO `videos`(`ID`, `type`, `name`, `date`, `processed`)
VALUES (NULL, 'auto', 'Lorem', '2018-04-05 00:00:00', 'no')...
Will I then be able to do something like this:
$update_sql = "SELECT * FROM `acc_change` where `date` < '2018-04-23 12:32:00'"
$sqlMsg = enterSql($update_sql);
and get all the recently added records?
IMPORTANT:
Normally I'd:
pull old data from the database and save it in arrays/objects
pull the new data and save in arrays/objects.
filter out what I need and make new arrays/objects.
create new insert SQL statements.
I am perfectly aware that this is a sollution to the problem, but that is NOT what I am asking. I am asking if/how you can insert/update and then access that new data right away.
My database functions:
function db($action){
static $conn;
$servername = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "life2020";
if ($action == "use"){
if ($conn === null){
$conn = mysqli_connect($servername, $dbuser, $dbpass, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
return $conn;
} else {
mysqli_close($conn);
}
}
function get_db_rows($sql){
$rows = array();
$conn = db("use");
$result = mysqli_query($conn, $sql) or die("Erro!: " . mysqli_error($conn));
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
}
mysqli_free_result($result);
return $rows;
}
function enterSql($sql){
$sqlMsg = "";
$conn = db("use");
if (mysqli_multi_query($conn, $sql)) {
$sqlMsg = "Entered data";
} else {
$sqlMsg = "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
return $sqlMsg;
}
SELECT * FROM table_name ORDER BY id DESC,LIMIT 2.
Related
I'm a newbie on php and I try to make a calendar for people travel information from db and want to show these info on the calendar's day so my problem is to connect MSSQL Server and take the values form db.My php pages work on localhost(wampp) and my calendar view perfectly but cannot get the value from DB.It does not give an error.But can not pull data.Could you please help me to find my fault.Thanks.
connect.php;
<?php
class DBO
{
private $server = "servername";
private $db_name = "dbname";
private $password = "pass";
private $username = "username";
private $conn;
private $database;
function Connect()
{
$this->conn = mssql_connect($this->server, $this->username, $this->password)
or die("Couldn't connect to SQL Server on " . $this->server);
$this->database = mssql_select_db($this->db_name, $this->conn)
or die("Couldn't open database " . $this->db_name);
}
function RunSql($sqlQuery)
{
return mssql_query($sqlQuery);
}
}
?>
query code;
<?php
include_once("db_connect.php");
$DBO = new DBO();
$DBO->Connect();
$query = "SELECT ID, TYPE, STARTDATE, ENDDATE FROM TABLENAME";
$query_results = $DBO->RunSql($query)
or die('Error in $query_menu. Error code :' . mssql_get_last_message() );
$calendar = array();
while( $results = mssql_fetch_assoc($query_menu_results) )
{
$calendar[] = array('ID' =>$rows['ID'],'TYPE' => $rows['TYPE'],'url' => "#","class" =>'event-important','start' => "$start",'end' => "$end");
}
$calendarData = array(
"success" => 1,
"result"=>$calendar);
echo json_encode($calendarData);
exit;
?>
<?php
I believe you're issue is from executing the SQL via...
$query_results = $DBO->RunSql($query)
...but using it via...
while( $results = mssql_fetch_assoc($query_menu_results) )
Basically, $query_results becomes $query_menu_results.
I use a variant of this to test MsSQL connectivity:
<?php
// connect to the server
$dbconn = mssql_connect('SEVER_NAME_OR_IP', 'MsSQL-User', 'MsSQL-User-Password');
if (!$dbconn) {
$message='unable to connect to the database: ' . mssql_get_last_message();
die($message);
}
// select the database
if (!mssql_select_db('DATABASE_NAME', $dbconn)) {
die('Unable to select the database!');
}
// execute a query. NOTE: Never use string concatenation in SQL statements. EVER!!!
$sql = "select * from information_schema.tables;";
$query = mssql_query($sql, $dbconn);
// consume the results
echo "<table border='1'><tr><th>Column A</th><th>Column B</th></tr>";
while ($row = mssql_fetch_row($query)) {
echo "<tr><td>";
echo $row[0];
echo "</td><td>";
echo $row[1];
echo "</td></tr>";
}
echo "</table>";
// clean up
mssql_free_result($query);
mssql_close($dbconn);
?>
SECURITY NOTE: Last I check, The mssql* doesn't support prepared statements. Please see PDO or sqlsrv*. This Question has good info on MsSQL prepared statements.
Solution:
I've reproduced your code and I've found these errors:
include_once("db_connect.php"); must be include_once("connect.php");
while ($results = mssql_fetch_assoc($query_menu_results)) { must be while ($results = mssql_fetch_assoc($query_results)) {
'ID' =>$rows['ID'], must be 'ID' => $results['ID'],
'TYPE' => $rows['TYPE'], must be 'TYPE' => $results['TYPE'],
missing $start and $end variables;
Working example:
Example is based on your code. I've left your erros in comment. Table definition is just to make working query.
Database:
CREATE TABLE [dbo].[TABLENAME] (
[ID] [numeric](10, 0) NULL,
[TYPE] [numeric](10, 0) NULL,
[STARTDATE] datetime NULL,
[ENDDATE] datetime NULL
) ON [PRIMARY]
INSERT [TABLENAME] (ID, TYPE, STARTDATE, ENDDATE)
VALUES (1, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
INSERT [TABLENAME] (ID, TYPE, STARTDATE, ENDDATE)
VALUES (1, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
SELECT ID, TYPE, STARTDATE, ENDDATE
FROM [TABLENAME]
connect.php
<?php
class DBO {
private $server = "servername";
private $db_name = "dbname";
private $password = "pass";
private $username = "username";
private $conn;
private $database;
function Connect() {
$this->conn =
mssql_connect($this->server, $this->username, $this->password) or
die("Couldn't connect to SQL Server on " . $this->server);
$this->database =
mssql_select_db($this->db_name, $this->conn) or
die("Couldn't open database " . $this->db_name);
}
function RunSql($sqlQuery) {
return mssql_query($sqlQuery);
}
}
?>
query.php
<?php
//include_once("db_connect.php");
include_once("connect.php");
$DBO = new DBO();
$DBO->Connect();
$query = "SELECT ID, TYPE, STARTDATE, ENDDATE FROM [TABLENAME]";
$query_results =
$DBO->RunSql($query)
or die('Error in $query_menu. Error code :' . mssql_get_last_message() );
$calendar = array();
//while ($results = mssql_fetch_assoc($query_menu_results)) {
while ($results = mssql_fetch_assoc($query_results)) {
$calendar[] = array(
//'ID' =>$rows['ID'],
'ID' => $results['ID'],
//'TYPE' => $rows['TYPE'],
'TYPE' => $results['TYPE'],
'url' => "#",
"class" => 'event-important',
//'start' => "$start",
//'end' => "$end"
);
}
$calendarData = array(
"success" => 1,
"result"=>$calendar
);
echo json_encode($calendarData);
exit;
?>
Output:
{
"success":1,
"result":[
{"ID":"1","TYPE":"1","url":"#","class":"event-important"},
{"ID":"1","TYPE":"1","url":"#","class":"event-important"}
]
}
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
I'm connecting to a cloud database through an ODBC connection:
$conn = odbc_connect('MYDATABASE','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql = "SELECT DATETIME_ID, NAME, Sum(CNDROP) AS DATA
FROM MY_TABLE
WHERE DATETIME_ID>='2014-09-28:00:00:00'
and DATETIME_ID<='2014-09-28 23:00:00'
and NAME IN ('CC2')
GROUP BY DATETIME_ID, NAME ORDER BY DATETIME_ID, NAME";
$rs = odbc_exec($conn,$sql);
if (!$rs) {
exit("Consulta fallida");
}
$result = odbc_exec($conn,$sql) or die(exit("Error en odbc_exec"));
print odbc_result_all($result,"border=1");
odbc_close($conn);
I can get the data, and print the data, but now I need insert that data into a MySQL database into my computer.
I don't have any idea how to do it, so I need help with an example. I tried to search on google but nothing was helpful.
Option 1:
Function to SELECT
function get_data_from_cloud(){
$conn=odbc_connect('CLOUD','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql="SELECT DATETIME, NAME, CNDROP
FROM TABLE1
WHERE DATETIME>='2014-09-28 00:00:00' and
DATETIME<='2014-09-28 23:00:00' and
NAME IN ('PETER')
GROUP BY DATETIME, NAME
ORDER BY DATETIME, NAME";
$result=odbc_exec($conn,$sql)or die(exit("Error en odbc_exec"));
$data = array();
while (odbc_fetch_row($result)) {
$data[]=array('DATETIME' => odbc_result ($result, "DATETIME"),
'NAME'=> odbc_result ($result, "NAME"),
'CNDROP'=> odbc_result ($result, "CNDROP"));
}
return $data;
}
Function to INSERT
function insert_cloud_data($cloud_data=array()){
$conn=odbc_connect('LOCAL','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
foreach($cloud_data as $data){
$sql = sprintf("INSERT INTO Prueba (DATIME, NAME, CNDROP)
VALUES ( '%s','%s','%s')",
$data['DATETIME'], $data['NAME'], $data['CNDROP']);
$rs = odbc_exec($conn,$sql);
if (!$rs) {
error_log("Consulta fallida");
}
}
odbc_close($conn);
}
Option 2:
Function to SELECT
function get_data_from_cloud(){
$conn=odbc_connect('CLOUD','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql="SELECT DATETIME, NAME, CNDROP
FROM TABLE1
WHERE DATETIME>='2014-09-28 00:00:00' and
DATETIME<='2014-09-28 23:00:00' and
NAME IN ('PETER')
GROUP BY DATETIME, NAME
ORDER BY DATETIME, NAME";
$result=odbc_exec($conn,$sql)or die(exit("Error en odbc_exec"));
$data = array();
while (odbc_fetch_row($result)) {
$data[]=array(odbc_result ($result, "DATETIME"),
odbc_result ($result, "NAME"),
odbc_result ($result, "CNDROP"));
}
return $data;
}
Function to INSERT
function insert_cloud_data($cloud_data=array()){
$conn=odbc_connect('LOCAL','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql = "INSERT INTO Prueba (DATIME, NAME, CNDROP)
VALUES (?, ?, ?)";
$stmt = odbc_prepare($conn, $sql);
if(!$stmt) die("could not prepare statement ".$sql);
foreach($cloud_data as $data){
odbc_execute($stmt, $data);
}
odbc_close($conn);
}
USAGE
$cloud_data = get_data_from_cloud();
insert_cloud_data($cloud_data);
Here is different approach.
Create $conn1 (cloud) and $conn2 (localhost). Query the $conn1 then use php while and insert command into $conn2.
$conn1 = (cloud);
$conn2 = (localhost);
$query = "SELECT ...";
$result = odbc_exec($conn1,$query);
while( fetch result data ) {
$query = "INSERT ....";
odbc_exec($conn2,$query);
}
this is my connection class
class Connection {
public function query($sql){
mysql_connect('localhost','root','') or die("Connection error ". mysql_error());
mysql_select_db('liontours') or die("Database error ". mysql_error());
$results = mysql_query($sql);
$last_inserted_id = mysql_insert_id();
return array('results'=>$results, 'last_id'=>$last_inserted_id);
}
}
this is my model
public function V_reg($v_no, $dl_no, $owner, $o_name, $o_nic, $i_date, $ex_date, $p_report, $nic, $s_name, $f_name, $initials, $dob, $stat, $v_type) {
$sql = "INSERT INTO `vehicledetails`(`vehicle_no`, `owner`, `owner_name`, `owner_nic`, `insured_date`, `ex_date`, `police_report`,`type`)
VALUES ('$v_no','$owner','$o_name','$o_nic','$i_date','$ex_date','$p_report','$v_type')";
$conn = new Connection();
//vehicle id of last inserted record
$vehicle_id = mysql_insert_id();
$results = $conn->query($sql);
$last_vehicle_record_id = $results['last_id'];
$fk_key = $last_vehicle_record_id;
//checking the first table insert successful if so do the second insert else must define counter measure in else part
if ($fk_key !== 0) {
$sql1 = "INSERT INTO driverdetails (id, vehicle_id, nic,sir_name,first_name,dlNo,initials,dob,status )
VALUES ('null', '$fk_key', '$nic','$s_name','$f_name','$dl_no', '$initials','$dob','$stat')";
$results = $conn->query($sql1);
}else{
die('transaction failed').mysql_error();
}
return $results;
}
}
i don't know what is wrong with this coding but it's not passing the data all the time it says transaction failed and no error given. just the text can some body tell me any thing wrong with this coding ? if there is no coding errors is it a problem with my database ?
I'm trying to insert some data into a mysql table but the process doesnt go through and I get nothing printed for the error. I don't think I'm outputting the errors correctly. Looking at php.net it seems like I'm doing the error handling properly but maybe I'm missing something.
Here is the code
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sqlInsert = $db->query("INSERT INTO transactions(`user_id`, `courses`, `invoice`, `start_date`, `end_date`, `mc_gross`, `email`) VALUES ('".$user_id."','".$trim."','".$invoice."','".$start_date."','".$end_date."', '".$email."')");
if($sqlInsert)
{
echo "Inserted successfully";
}
else
{
printf("Error: ", $db->error);
}
The values for the variables are as follows
$custom = $_SESSION['custom'];
$user_id = $_POST['userID'];
$pwd = $_POST['password'];
$email = $_POST['email'];
$start_date = date('Y-m-d');
$end_date = date (('Y-m-d'), strtotime('+120 days'));
$invoice = date('Ymd'). mt_rand(1252,10000);
$invoice_check = $db->query("SELECT `invoice` FROM `transactions` WHERE `invoice` = $invoice");
while ($rows = $invoice_check->fetch_assoc())
{
$invoice = date('Ymd'). mt_rand(1252,10000);
}
$mc_gross = $_SESSION['subtotal'];
$trim = rtrim($custom, ",");
the var_dump for $trim is string(17) "bio_01,calculus_01" and the other variables just echo out normally as you'd expect.
Any ideas?
EDIT Updated the code with $db instead of $sqlInsert. Still no output for an error.
Change:
printf("Error: ", $sqlInsert->error);
to:
printf("Error: %s", $db->error);
You can't read the error property of false, because it's not an object. And you're missing the %s in the printf format string to substitute the argument.