i am using this code to add values to database
<?php
$debdes = $_POST['debdes'];
$debamt = $_POST['debamt'];
$crdes = $_POST['crdes'];
$cramt = $_POST['cramt'];
$date = $_POST['date'];
include_once ("db.php");
$ucbook = "INSERT INTO cbook(debdes,debamt,crdes,cramt,date) VALUES ('$debdes','$debamt','$crdes','$cramt','$date');";
if (mysql_query($ucbook))
echo "One Record Updated Successfully with the following details <br/>";
else
echo mysql_error();
?>
now i want that when query pass this show me that which values are added like this
"Following record is updated successfully
debamt = 1000
debdes = test
end "
if the query does not fails, you can just show your values:
.
.
.
if (mysql_query($ucbook)){
echo "One Record Updated Successfully with the following details <br/>";
echo "debdes=$debdes <br>" ;
echo "debamt=$debamt <br>" ;
echo "crdes=$crdes <br>" ;
echo "cramt=$cramt <br>" ;
echo "date=$date <br>" ;
echo "end";
}
else
{
echo "Error while inserting data :".mysql_error()."<br/>";
}
.
.
.
there are two ways to do it:
if you one of the fields that you are inserting is a primary key, then search the table for the record you updated, and then display the resultant data.
If your primary key is generated automatically using auto_increment, then use mysql_insert_id.
Cheers,
jrh
Related
eBay Platform Notifications recommends periodic polling of the GetOrders API to ensure each and every order is received.
In my case, I have Platform Notifications set-up to parse the XML file received and insert it into a MySQL database using PHP.
Now I am looking to, as recommended, "double pass" using GetOrders, which should essentially give me duplicates for each and every single row (or order).
My structure is rather straightforward. But I have a UNIQUE INDEX for OrderLineItemID which, to my understanding, is the unique identifier for each eBay Order.
Is there a better way to do this than I am currently doing?
//retrieve and escape variables for insertion//
$sql = "INSERT INTO eBayOrders (OrderLineItemID, SalesRecordNumber, BuyerUserID, BuyerEmail, Title, SKU, Quantity, TransactionPrice)
VALUES ('".$orderlineitemid."', '".$recordnumber."', '".$buyeruserid."', '".$buyeremail."', '".$title."', '".$sku."', '".$qty."', '".$transactionprice."')";
}
if ($connect->query($sql) === TRUE) {
echo "New Record Created Successfully";
} else {
echo "Error: " . $sql . "<br />" . $connect->error;
$connect->close();
die();
}
Because of my UNIQUE ON OrderLineItemID, when a duplicate order comes in, the query will result in an error, close the connection, and then exit the script.
I've thought about first checking to see (maybe using a SELECT statement) if the row exists, and then trying an insert, but I'm doing a foreach loop of up to 100 orders using the GetOrders API to run my SQL queries, and it seems like just allowing it to fall to error might be a quicker option, but I'm weary on if this can cause issues down the line.
In all, I'm not familiar with best practices for MySQL "double passes". Anyone have any insight on the best way to conduct this?
edit: here is my entire foreach loop:
foreach ($orders as $order) {
$i++;
$buyeruserid2 = $order->BuyerUserID;
$buyeruserid = mysqli_real_escape_string($connect, $buyeruserid2);
// $extendedorderid = $order->TransactionArray->Transaction->ExtendedOrderID;
$buyeremail2 = $order->TransactionArray->Transaction->Buyer->Email;
$buyeremail = mysqli_real_escape_string($connect, $buyeremail2);
$salesrecordnumber2 = $order->TransactionArray->Transaction->ShippingDetails->SellingManagerSalesRecordNumber;
$salesrecordnumber = mysqli_real_escape_string($connect, $salesrecordnumber2);
$orderlineitemid2 = $order->TransactionArray->Transaction->OrderLineItemID;
$orderlineitemid = mysqli_real_escape_string($connect, $orderlineitemid2);
$title2 = $order->TransactionArray->Transaction->Item->Title;
$title = mysqli_real_escape_string($connect, $title2);
$sku2 = $order->TransactionArray->Transaction->Item->SKU;
$sku = mysqli_real_escape_string($connect, $sku2);
$quantitypurchased2 = $order->TransactionArray->Transaction->QuantityPurchased;
$quantitypurchased = mysqli_real_escape_string($connect, $quantitypurchased2);
$transactionprice2 = $order->TransactionArray->Transaction->TransactionPrice;
$transactionprice = mysqli_real_escape_string($connect, $transactionprice2);
echo $i;
echo "\n";
echo "BuyerUserID: " . $buyeruserid . "\n";
echo "extendedorderid: " . $quantitypurchased . "\n";
echo "BuyerEmail: " . $buyeremail . "\n";
echo "SellingManagerSalesRecordNumber: " . $salesrecordnumber . "\n";
echo "OrderLineItemID: " . $orderlineitemid . "\n";
// echo "ExtendedOrderID: " . $transaction->ExtendedOrderID . "\n";
echo "Title: " . $title . "\n";
echo "SKU: " . $sku . "\n";
echo "QuantityPurchased: " . $quantitypurchased . "\n";
echo "TransactionPrice: " . $transactionprice . "\n";
echo "\n";
$sql = "INSERT INTO eBayOrders (OrderLineItemID, SalesRecordNumber, BuyerUserID, BuyerEmail, Title, SKU, Quantity, TransactionPrice)
VALUES ('".$orderlineitemid."', '".$recordnumber."', '".$buyeruserid."', '".$buyeremail."', '".$title."', '".$sku."', '".$qty."', '".$transactionprice."')";
if ($connect->query($sql) === TRUE) {
echo "New Record Created Successfully";
} else {
echo "Error: " . $sql . "<br />" . $connect->error;
$connect->close();
die();
}
}
To avoid an error when an INSERT fails due to a unique key constraint, we can use the IGNORE option on the INSERT statement.
INSERT IGNORE INTO eBayOrders ...
If you use the IGNORE modifier, errors that occur while executing the INSERT statement are ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row is discarded and no error occurs. Ignored errors generate warnings instead.
But this also affects error conditions other than duplicate key exceptions.
As another option, we can use INSERT ... ON DUPLICATE KEY ...
Documentation available here:
Reference: https://dev.mysql.com/doc/refman/5.7/en/insert.html
use php variable in name of mysql create table
I want to use a PHP variable ( $userAltId ) as the name of the SQL table I am creating. However, despite looking at several examples, I have been unable to successfully create a table with this PHP variable. Using echo I have shown that the variable ( $userAltId ) does contain the predicted value, and if I plug in that value instead of the variable I can successfully create the table.
My latest attempt at the code is below, notice I use $useAltId three times, from creating, inserting, and selecting. Thanks for the help!
<?php
$con=mysqli_connect('localhost', 'alexpnqo_johnny', '?KlI+TtfNEIO', 'alexpnqo_johnny');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
session_start();
$userAltId = $_SESSION['userAltId'];//I am passing $userAltId from another php file
// escape variables for security
$FBname = mysqli_real_escape_string($con, $_POST['FBname']);
echo $userAltId;//echos desired value
$sqlFriendList="INSERT INTO '$userAltId' (FacebookFriend)
VALUES ('$FBname')";
if (mysqli_query($con,$sql)) {
echo "Table created successfully";
} else {
echo "Error creating table: " . mysqli_error($con);";
}
echo "You have added ";
echo $FBname;
echo " to your friend's list!";
echo "<br>";
echo "Below is your friends list";
echo "<br>";
echo "<br>";
$result = mysqli_query($con, "SELECT FacebookFriend FROM '$userAltId'");
echo "<table border='1'>
<tr>
<th>Friends List</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FacebookFriend'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Use backticks $userAltId to all your queries (table name) so that it'll read your variable even spaces.
$sqlFriendList="INSERT INTO `$userAltId` (FacebookFriend) VALUES ('$FBname')";
i have simple db that it is filled by a form from a page, all is ok in the entry.
i have 2 fields in the database are: all_students and current_students filled by the user in the form that i want to calculate
the trick is that i am echoing only the latest db record in the output page.. to give me only the latest data inserted in the form...
now, i want to create a new field that give me the absent students automatically (all - current)
what i have tried, i read that i can NOT create a new calculated field in the db, it is not an excel, so i am trying to echo the calculation results of these 2 fields, to a new value that is the "absent students"
what you suggest? please help, here is my code
<?php
$con=mysqli_connect("localhost","root","PasswordHere","DBnameHere");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT id, class, all_students, current_students FROM students ORDER BY id DESC LIMIT 1");
while($row = mysqli_fetch_array($result))
{
echo "Class: " . $row['class'] . "<br>";
echo "All students: " . $row['all_studnets'] . "<br>";
echo "Current students: " . $row['current_studnets'] . "<br>";
echo "Absent students: " . $row['all_studnets'] . - . $row['current_studnets'] . " <br>";
}
mysqli_close($con);
?>
You only put dot (.) if you want to concatenate a string. Please remove the dot since you are subtracting.
echo "Absent students: ";
echo floatval($row['all_studnets']) - floatval($row['current_studnets']);
echo "<br>";
Try this line
echo "Absent students: " . $row['all_studnets'] - $row['current_studnets'] . " <br>";
Insted of this
echo "Absent students: " . $row['all_studnets'] . - . $row['current_studnets'] . " <br>";
I'm a little bit confused why it does not work.
What i want is that control db if for ex 2012-02-21 exist in DB delete it and insert again but it does not work why
my full code is that but else statement doesnt work :S
$ga->requestAccountData();
$mysql = new mysql();
$mysql->connect();
// $startDate = date("Y-m-d");
$startDate = "2012-02-21";
$dbResult = mysql_query("select * from profiles where profile_Date='".$startDate."'");
$query = mysql_num_rows($dbResult);
if($query > 0)
{
mysql_query("delete from profiles where profile_Date='".$startDate."'");
foreach ($ga->getResults() as $result) {
$ga->requestReportData($result->getProfileId(),array('eventCategory','eventAction'),array('totalEvents'),$sort_metric=null,$filter='eventAction==InitPlayer',$start_date=$startDate,$end_date=$startDate);
foreach($ga->getResults() as $result2)
{
echo $result;
echo $result2->geteventCategory()."<br />";
echo $result2->geteventAction();
echo $result2->gettotalEvents();
"<br />";
"<br />";
"<br />";
$mysql->query("insert into profiles values(" . $result->getProfileId() . ",'" . $result . "','".$result2->geteventCategory()."','".$result2->geteventAction()."','".$result2->gettotalEvents()."','".$startDate."')");
}
}
}
else
{
foreach ($ga->getResults() as $result) {
$ga->requestReportData($result->getProfileId(),array('eventCategory','eventAction'),array('totalEvents'),$sort_metric=null,$filter='eventAction==InitPlayer',$start_date=$startDate,$end_date=$startDate);
foreach($ga->getResults() as $result2)
{
echo $result;
echo $result2->geteventCategory()."<br />";
echo $result2->geteventAction();
echo $result2->gettotalEvents();
"<br />";
"<br />";
"<br />";
$mysql->query("insert into profiles values(" . $result->getProfileId() . ",'" . $result . "','".$result2->geteventCategory()."','".$result2->geteventAction()."','".$result2->gettotalEvents()."','".$startDate."')");
}
}
}
You should use mysql_num_rows to count the results selected and not mysql_affected_rows which applies to queries altering data (insert, update, delete etc.)
$result = mysql_query("select * from profiles where profile_Date='".$startDate."'");
$count = mysql_num_rows($result);
if($count > 0) {
...
}
http://php.net/manual/en/function.mysql-num-rows.php
Why you need to first delete and then insert? you can use update query as well. Also what is the data type of the field profile_Date ? Is it set date or date and time?
You can use MySQL's REPLACE functionality (docs).
It basically works like INSERT, with the exception that if a value with the same key already exists in the database, at first the existing value will be removed and afterwards the new value will be inserted as completely new entry. If there is no existing value, it will behave like INSERT.
Watch out for the differences to UPDATE
The difference to UPDATE is hidden in the details:
since an existing value will actually be removed, all referenced foreign keys constraints will be removed too.
UPDATE will just update the values provided, with INSERT the other columns will get the default value (practical example: a field name timestamp_created with the default value of CURRENT_TIMESTAMP will be unchanged in an UPDATE statement, but will display the current time in a REPLACE statement)
i am using insert into db(fname,lname) values ('$fname','$lname')
command i want that when this query passes on the nest page it show me which fname and which lname is passed or added like this statement
Following recorded is updated in database successfully
first name = abc
last name = xyz
Store the query in a variable, execute and print it out:
$query = "insert into db(fname,lname) values ('$fname','$lname')";
mysql_query($query);
echo $query;
Or, if you want to print just the variables, why can't you just do:
echo 'firstname: '.$fname.' ';
echo 'lastname: '.$lname;
If this is not what you needed, please clarify your question.
$query = "insert into db(fname,lname) values ('$fname','$lname')";
if(mysql_query($query))
{
echo "Following recorded is updated in database successfully\n";
echo "first name = $fname \n";
echo "last name = $lname \n";
}