I want to get last insert id from my table cart in my else statement after the insert. But I am not getting the id.
Please check my code and suggest what am I doing wrong:
// Check to see if the cart COOKIE exists
if ($cart_id != '') {
// Here I want to update but not getting $cart_id, so everytime insert query fire in else statement
}else{
$items_json = json_encode($item);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ");
$cart_id = $db->insert_id; // Here is the problem
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}
Your suggestions would be welcome.
Instead of:
$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ");
$cart_id = $db->insert_id; // Here is the problem
Use this, directly from the documentation:
$query = "INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ";
mysqli_query($db, $query);
$cart_id = mysqli_insert_id($db);
Get the identity column value AFTER the insert:
create table student (
id int primary key not null auto_increment,
name varchar(20)
);
insert into student (name) values ('John');
select ##identity; -- returns 1
insert into student (name) values ('Peter');
select ##identity; -- returns 2
Or get the next auto incremental value before insert:
$query = $db->query("SHOW TABLE STATUS LIKE 'cart'");
$next = $query->fetch(PDO::FETCH_ASSOC);
echo $next['Auto_increment'];
Related
I'm trying to loop through the results of a mysql query in php, the output of the query is an array similar to [10201,10202]. I want to take the results and loop it to the variable named id in my javascript function and loop it through the url of my ajax call. The goal is to take the id and use it in a sql query on another page to change the date of the id in our database.
mysql query:
<?php
// sql query for # print all open orders function
$sql = "SELECT Order_PID
FROM `Order`
WHERE SHIPDATE IS NULL
AND Address1 IS NOT NULL;";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)) {
$order[] = $row['Order_PID'];
}
?>
javascript function:
I'm trying to use a forEach function to iterate through the results of the array.
$('button#printOpenOrders').on('click', function(e) {
if(confirm("Are you sure you want to print all open orders and mark them as pending?")) {
e.preventDefault();
// prints all open orders
window.open("/resources/scripts/allOpenPDF.php");
var arr = $order;
arr.forEach(function(id) { // <====this function
$.ajax({
url: "/resources/scripts/pending-order.php?id=" + id, // <===this variable
datatype : "string",
success : function(data) {
location.reload(true);
}
})
})
}
});
and if it helps here is my callback script
<?php
// login validation
session_start();
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true) {
$url = $_SERVER['DOCUMENT_ROOT'].'/index.php';
header("Location: ../../index.php");
}
// establish connection to database
include $_SERVER['DOCUMENT_ROOT'].'/resources/scripts/dbconnect.php';
$conn = openConnection();
// capture id
$id = $_GET['id'];
$pendingDate = date_create_from_format("m/d/Y", "07/26/1996");
$pendingDate = date_format($pendingDate, "Y-m-d H:i:s");
$sql = $conn->prepare("UPDATE `Order`
SET SHIPDATE = ?
WHERE Order_PID = ?");
$sql->bind_param("si", $pendingDate, $id);
$sql->execute();
echo "success";
closeConnection($conn);
?>
If parts of my code don't make sense, I'm new to this and I am using my currently limited knowledge to frankenstein all of this together. Any nudges in the right direction would be super helpful.
You can output $order variable contents, but you need to use PHP and also you must encode it using json format, so this could actually work:
var arr = <?PHP echo json_encode($order); ?>;
But it is error-prone, the syntax is not really nice to read, and if that variable somehow becomes in the format you are not expecting it could lead to another JavaScript syntax error.
But the best way in my opinion would be to make an AJAX request and get those order IDS, and after that you could create another AJAX request that would send all those Order IDS,
so you wouldn't need .forEach stuff and your logic of handling multiple orders need to be modified in order to accommodate for these changes.
But since you already have those IDS in PHP I mean stored in $order variable, you could just encode it and send it all the ids at once in a single request.
I am trying to get data from a json file to be loaded into my wordpress site. I would like to get the price from the matching name of the product of the site that I crawled. I need the name of the product to match the product attribute I added into the product page on wordpress then to get the price if the name matches the attribute I added. I don't know if I am making sense, but here is my code so far. It partially worked, but it did the same price across all my products. I am newer to php so can someone assist?
<?php
$str = file_get_contents('/run_results_apmex.json');
// decode JSON
$json = json_decode($str, true);
// get the data
$coinPrice = $json['coin'][1]['price'];
// echo it
if($json['name'] == $product->get_attribute[ 'Apmex Vendor Name' ]){
echo $coinPrice;
}
else{
echo 'No results found';
}
?>
You need to loop the json array to check the product attribute and get the price.
$str = file_get_contents('/run_results_apmex.json');
// decode JSON
$json = json_decode($str, true);
// default value
$coinPrice = "No results found";
$product_attribute = '1 oz Gold American Eagle BU (Random Year)';
// loop the json array
foreach($json['coin'] as $value){
// check the condition
if($value['name'] == trim($product_attribute)){
$coinPrice = $value['price']; // get the price
break; // exit the loop
}
}
echo $coinPrice;
Or you can create a recursive function to check the in_array
$str = file_get_contents('http://gold.explorethatstore.com/wp-content/themes/divi-ETS-child-theme/run_results_apmex.json');
// decode JSON
$json = json_decode($str, true);
// here I am passing the string instead of $product->get_attribute[ 'Apmex Vendor Name' ]. replace it in your code
$product_attribute = '1 oz Gold American Eagle BU (Random Year)';
$coinPrice = ($check = in_array_recursive(trim($product_attribute), $json['coin'])) ? $check['price']: 'No results found';
echo $coinPrice;
// output is $1,426.19
function in_array_recursive($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_recursive($needle, $item, $strict))) {
return $item;
}
}
return false;
}
How do I check if the user already created the same LRN ?
and when I press the save button twice it creates two user with the same info
how do I prevent it ?
jQuery('#save_voter').submit(function(e){
e.preventDefault();
var FirstName = jQuery('.FirstName').val();
var LastName = jQuery('.LastName').val();
var Section = jQuery('.Section').val();
var Year = jQuery('.Year').val();
var LRN = jQuery('.LRN').val();
var Password = jQuery('.Password').val();
e.preventDefault();
if (FirstName && LastName && Section && Year && LRN && Password){
var formData = jQuery(this).serialize();
jQuery.ajax({
type: 'POST',
url: 'save_student.php',
data: formData,
success: function(msg){
showNotification({
message: "Student Successfully Added",
type: "success",
autoClose: true,
duration: 5
});
By creating a unique constraint on the username field. It seems that in your case the LRN field is the username field. Make it unique by
ALTER TABLE users ADD UNIQUE INDEX uname on users (LRN);
Then you can try something like this to tell the end user that the username is duplicated.
try{
$res =$connection->query(your user insert);
}catch(Exception $e){
echo 'Sorry already exists';
}
You need to do 3 steps :
Check manually First Name and Last Name already exists or not in PHP file
In resultset contains more than 0 records, then return false which means record already exists.
In JQuery, if its getting false, then show an error message that record already exists.
Further, as #kongkang said in comments that the field LRN is as username.
then still you need to do 3 steps :
Make that field as unique in database table
Add if condition on insertion query (PHP File) that if return false it means record already exists
in Jquery, if returning value is false, then show error message.
Add a unique index to your database for a unique field.I hope LRN is there for you. Then
MYSQL:
ALTER TABLE users ADD UNIQUE (LRN)
SQL SERVER:
ALTER TABLE [users] ADD CONSTRAINT UC_LRN UNIQUE ([LRN]);
When you try to insert duplicate LRN database error will come automatically for Codeigniter. Without it you have to check manually.
I am trying to loop through data to make a chat system.
I have made a php function:
function getLatestMessageTime() {
$handler = new PDO('mysql:host=localhost;dbname=*****', '******', '*******');
// Set the query \\
$query = $handler->query('SELECT `time` FROM `messages`');
// Loop through the data \\
$latestTime = 0;
while ($row = $query->fetch()) {
if ($row['time'] > $latestTime) {
$latestTime = $row['time'];
};
};
// Return the latest message time \\
Return $latestTime;
}
And I set my looping jQuery code:
var latestTime = <?php echo getLatestMessageTime(); ?>;
latestTimeLoop();
function latestTimeLoop() {
if (latestTime < <?php echo getLatestMessageTime(); ?>) {
$("#container").load('ajaxLoad.php?time='+latestTime);
};
document.log(latestTime + " - " + <?php echo getLatestMessageTime(); ?>);
setTimeout(latestTimeLoop, 200);
}
But when I change the time in phpMyAdmin to be much higher than the rest of the data, it doesn't update in my console.logs. It seems like my query isn't occuring more than once within my function, it only grabs the data once instead of requesting it each time my javascript code loops.
Is there any way to reset the query each time to it grabs new info each loop?
View Full Code
use ORDER BY in your query and also limit the query to one.
$query = $handler->query('SELECT `time` FROM `messages` ORDER BY `time` DESC LIMIT 1');
Only last record details is needed to get the latest message time. thats why i said to use limit and modify php code according to it.
<?php
$id = rand(10000,99999);
$shorturl = base_convert($id,20,36);
echo $shorturl;
$db->query("INSERT INTO maps (id, url, user_id, locationData, userData) values ( null, '$shorturl', null, '$locationData','$userData')");
Using the above PHP I have been trying generate a unique shorturl which gets stored into a Database and then gets sent to javascript to tell the client side the values echoed.
In an example I tested the above code and in Javascript it console.logged lyhc but when I checked the Database it had the following 6c796863
The database row is set up like url varchar(255) utf8_bin
Am I doing something wrong here?
Your JS code must be taking your output in a different type.
I'm using this function to generate random strings:
function createRandomCode($length='30'){
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$code= '';
while ($i++ < $length){
$code = $code. substr($chars, rand() % 33, 1);
}
return $code;
}
It might be helpful.