Error when adding FIRST record to table - php

Ok. I ran into an issue. My code is able to insert records into my merchandise table. I truncated the table and a record is still inserted into the table but with an error "Undefined variable last_id". I assume that this is because when the table was truncate, there isn't a previous id since the record being inserted is the FIRST. Can someone help me resolve this issue. Thanks!
$sql = "SELECT m_id FROM merchandise";
$result = mysqli_query($connection, $sql);
while($row = mysqli_fetch_assoc($result)) {
$last_id = $row["m_id"];
}
$next_id = $last_id+1;
$conc = number_format($next_id/100,2,'-','');
$query = "INSERT INTO merchandise (mfr,type,description,mer_sku,price,qty) ";
$query .="VALUES ('$mfr','$type','$desc','MR{$mfr}{$conc}','$price','$qty')";
$add_sku_query = mysqli_query($connection, $query);

Declare last id as zero in case there are no rows.
$last_id = 0;
$sql = "SELECT m_id FROM merchandise";
$result = mysqli_query($connection, $sql);
while($row = mysqli_fetch_assoc($result)) {
$last_id = $row["m_id"];
}
$next_id = $last_id+1;

Related

Expiry date IF santance is not working with MYSQL UPDATE

I have table with many rows. I have exp date and I want to change status of those rows where date is already exp.
It work well if I do not use UPDATE. If I just echo them. But when I want to UPDATE status of this row to 0, problems start. My problem is that it change only 1 row and not all of them that needs to be whit status 0.
$sql = "SELECT * FROM table";
$result = mysqli_query($conn, $sql);
$resultcheck = mysqli_num_rows($result);
$id = $row['id'];
if($resultcheck > 0) {
while($row = mysqli_fetch_assoc($result)) {
$expdate = $row['date'];
$exp = strtotime($date);
$today = date('m/d/Y');
$td = strtotime($today);
if($td>$exp) {
$status=0;
$sql = " UPDATE table SET status = '$status' WHERE ID = '$id' ";
$result = mysqli_query($conn, $sql);
}
}
}
Any advice how to fix that, I tried several option but nothing worked.
Use row['id'] instead of $id.
$sql = " UPDATE table SET status = '$status' WHERE ID = 'row['id']' ";
Rename $result for update. You are reusing the same variable name, hence, after a success update, it will set $result to true and the while loop will stop.

Update same record in different tables

i have two tables:
table 1 = userfiles
table 2 = uploaded
Both tables have multiple columns but have one same column: Title ('ID's are different)
if i update the value of one userfiles.Title it should also update the value of the same uploaded.Title.
if(isset($_POST["btnSubmit"])){
$id = $_GET['id'];
$titlefield = $_REQUEST['titlefield'];
$Title = 'Title';
$errors = array();
$conn = mysqli_connect("localhost","root","12345","phpfiles");
$query = "UPDATE userfiles, uploaded
SET userfiles.$Title='$titlefield',
uploaded.$Title='$titlefield'
WHERE
userfiles.ID = '$id'
uploaded.title='$titlefield'";
$update2 = mysqli_query($conn, $query);
mysqli_close($conn);
$count = count($errors);
if($count != 0){
foreach($errors as $error){
echo $error."<br/>";
}
}
}
if i update (through php web form) userfiles.title(aaaaa) to 'ddddd' it should also update uploaded.title(aaaaa) to (ddddd)
but nothing gets updated
Run first update
$query = "UPDATE userfiles
SET userfiles.$Title='$titlefield'
WHERE
userfiles.ID = '$id'";
$update2 = mysqli_query($conn, $query);
Run second update
$query = "UPDATE uploaded
SET uploaded.$Title='$titlefield'
WHERE
uploaded.title='$titlefield'";
$update2 = mysqli_query($conn, $query);

Using a good SQL query instead of PHP code

I have a page that is taking a kind of long time to load, and I'm almost sure that this is caused by too many sql requests (AKA caused by my bad SQL skills). Is there anyway to join these 3 queries into one?
What I want to do with this query is to try to select a specific id from cardapios and, if there is anything there (if $num_rows > 0) the only thing I want to do is select that id. If there is nothing there, then I want to insert something and then select the id of that.
$query = "SELECT id FROM cardapios WHERE nome='$nome'";
$sql = mysqli_query($con,$query);
$num_rows = mysqli_num_rows($sql);
if ($num_rows > 0){
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
$num_rows = 0;
}}else{
$query = "INSERT INTO cardapios (nome, kcal, semana)
VALUES('$nome', '$kcal', '$semana')" or die(mysqli_error($con));
$sql = mysqli_query($con,$query);
$query = "SELECT id FROM cardapios WHERE nome='$nome' ";
$sql = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
}
}
I am trying to put all of this into one query but getting nowhere. Is there anyway to use just one query for doing all of this?
Thanks in advance!
You can replace the last query by getting the mysqli_insert_id($con); as you already have the insert id available after the insert
$query = "SELECT id FROM cardapios WHERE nome='$nome'";
$sql = mysqli_query($con,$query);
$num_rows = mysqli_num_rows($sql);
if ($num_rows > 0){
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
$num_rows = 0;
}
}else{
$query = "INSERT INTO cardapios (nome, kcal, semana)
VALUES('$nome', '$kcal', '$semana')" or die(mysqli_error($con));
$sql = mysqli_query($con,$query);
if ( $sql !== false) { // did insert work
$_SESSION['id_cardapio'] = mysqli_insert_id($con);
} else {
// insert did nto work??
}
}

why does my while loop stop after executed another query inside?closed

my while loop stops after executed another query inside... can you correct my codes? I want to update the column status in table ordered_items_supplier to "Pending" when the pi_number is found in the table purchased_items_supplier and if not found the column status is "Active".
$sql2 = "select * from ordered_items_supplier";
$result = $connect->query($sql2);
if($result->num_rows > 0){
while ($row = $result->fetch_assoc()) {
$pi_number = $row['pi_number'];
$sql = "select * from purchased_items_supplier where pi_number = '$pi_number'";
$result = $connect->query($sql);
if($result->num_rows > 0){
while ($row2 = $result->fetch_assoc()) {
$pi_number = $row2['pi_number'];
$sql = "update ordered_items_supplier set status = 'Pending' where pi_number = '$pi_number'";
$query = $connect->query($sql);
}
}else{
$sql = "update ordered_items_supplier set status = 'Delivered' where pi_number = '$pi_number'";
$query = $connect->query($sql);
}
}
}
here's my mysql.. it should update the status "Delivered" in ID 11
The problem is overwriting the same variable each time.
Check that you use $result for the outer and inner query both.That's why the problem occur. So don't overwriting the $result variable.

Sending information from a newly created record to a different MySQL table

I'm making a form that submits a story into a MySQL table called 'work'. I want to later take the id of the newly created record and put the information into a different table.
But when I submit the story, it says:
$workid is undefined.
I can't see the problem though because I believe I've defined it?
<?php
if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) {
$title = strip_tags($_POST['title']);
$story = strip_tags($_POST['story']);
$title = mysqli_real_escape_string($db, $title);
$story = mysqli_real_escape_string($db, $story);
$genre = $_POST['genre'];
$rating = $_POST['rating'];
$query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
$result = $db->query($query);
$data = $result->fetch_assoc();
if ($data['count'] > 0) {
echo "<p>Story already exists!</p>";
} else {
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$query = "SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc())
$workid = $row["id"]; //workid is written here but still considered undefined
}
$query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
$result = $db->query($query);
$query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
$result = $db->query($query);
if ($result) {
echo "<p>Story submitted!</p>";
} else {
echo "SQL Error: " . $db->error;
}
}
}
?>
You never did a $db->query() on your INSERT INTO... query string, so it was never inserted, and was overwritten by your SELECT id ... query.
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$db->query($query); // Missing this $db->query()
$query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row= $result->fetch_assoc())
$workid = $row["id"];}
Your $workid might not be initialized, depending on your condition and the result of your SQL query: so try to avoid next operations that will causes warnings/errors by using continue or else

Categories