Data will not enter database - php

For some reason $query3 and $query4 will throw out this error
Couldn't enter data: You have an error in your SQL syntax; check the
manual that corresponds to your MariaDB server version for the right
syntax to use near 'WHERE job_id = '35' at line 1
I cannot see why it is doing this the query syntax seems fine.
Table structure:
https://imgur.com/a/ioOKZ
Actionpage7:
session_start();
require 'config.php';
$id = $_SESSION['login_user'];
$bidid = $_POST['bid_id'];
$jobid = $_POST['job_id'];
$bidder_id = $_POST['bidder_id'];
$bid_amount = $_POST['bid_amount'];
$query = " UPDATE bid SET status = '1' WHERE bid_id = '$bidid'";
$success = $conn->query($query);
$query2 = " UPDATE job SET accepted = '1' WHERE job_id = '$jobid'";
$success = $conn->query($query2);
$query3 = "INSERT into job (accepted_bidder) VALUES('" . $bidder_id . "') WHERE job_id = '$jobid'";
$success = $conn->query($query3);
$query4 = "INSERT into job (accepted_bid) VALUES('" . $bid_amount . "') WHERE job_id = '$jobid'";
$success = $conn->query($query4);
if(!$success) {
die("Couldn't enter data: " . $conn->error);
}
echo "Thank You For Contacting Us <br>";
header("location: myjobs.php");
$conn->close();

You can do it in one query:
UPDATE job SET
accepted = '1',
accepted_bidder = 'value',
accepted_bid = 'value'
WHERE job_id = '$jobid'
As stated in comments - your code is vulnerable to SQL injections. Refer to this topic to know more.

You have two types of queries here.
Query 1 and 2 are updates
$query = " UPDATE bid SET status = '1' WHERE bid_id = '$bidid'";
$query2 = " UPDATE job SET accepted = '1' WHERE job_id = '$jobid'";
They say UPDATE table and SET column = value WHERE condition is true. As the name implies this updates existing rows. The condition is used to limit the rows that the update is applied to. Without it every bid would have its status set to 1 and every job would be accepted. Which is probably not good.
Query 3 and 4 are inserts
$query3 = "INSERT into job (accepted_bidder) VALUES('" . $bidder_id . "') WHERE job_id = '$jobid'";
$query4 = "INSERT into job (accepted_bid) VALUES('" . $bid_amount . "') WHERE job_id = '$jobid'";
They say INSERT into table using (columns...) having VALUES(values...) WHERE condition. Again the name says it all, INSERT inserts new rows into the table. Now the question is what is the WHERE clause supposed to do?
Are you trying to limit the inserted rows to only those that match your condition? Well you are the one saying what rows to insert so you don't really need to do that. Are you trying to set values on the rows to be inserted? Well you can do that by adding more columns to the column list and their respective values to the value list. So it turns out there isn't really much point to a WHERE clause on an INSERT statement like that and in fact it's not allowed. That's what the error is trying to tell you.
As the other answer says you probably want to update an existing job and not insert a new one anyways.

Related

Search a database to update the results

I am taking a users input and storing it in a database, however I want to be able to update the records if a user adds more information. So I want to search the database find the server with the same name and update the the last downtime and the number of downtimes.
$connect = mysqli_connect("localhost", "Username", "Password","Test_downtime");
if (!$connect)
{
die("Connection failed: " . mysqli_connect_error());
}else
{
echo "Connected successfully\n";
}
$servername = $_GET["server_name"];
$downtime = $_GET["downtime"];
$time_now = time();
$result = mysqli_query($connect, "SELECT COUNT(*) FROM `Test_downtime`.`Downtime` WHERE `Server_Name` = '$servername'");
$row = mysqli_fetch_array($result);
// If no downtime have been reported before
if ($row[0] == 0){
$sql = mysqli_query($connect, "INSERT INTO `Test_downtime`.`Downtime` (ID, Server_name, First_downtime, Last_downtime, Num_of_downtime,Total_downtime) VALUES (NULL, '$servername', '$time_now','$time_now',1,'$downtime'); ");
if ($sql==true) {
echo $servername . " has has its first downtime recorded\n";
}
}
//If users is already in the database
else{
$numdowntime = ($row["Num_of_downtime"] + 1);
$id = ($row["ID"]);
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
if ($sqlupdate == TRUE) {
echo "Oh No! " . $servername . " has had ". $numdowntime ." of downtimes" ;
}
}
?>
The program works fine if the server is not already in the database, the problems arise if the server is already in the database. I get the message saying it has been updated yet nothing happens to the database. How do i make it so it search and updates the records for the searched item.
So nothing append since you do not execute the sql statement ^^
Take a look here :
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
You need to use :
$sql = mysqli_query($connect, $sqlupdate);
Just after it in order to execute it.
Or at least change it to
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
Btw there is other problem but here is the main one [check out the other answer in order to found another one ]
you are fetching the result as indexed array
mysqli_fetch_array($result);
and here you are accessing results as associative array
$numdowntime = ($row["Num_of_downtime"] + 1);
change your query to
mysqli_fetch_assoc($result);
use
mysqli_num_rows($result);
to checking if you have any data
change
if ($row[0] == 0){}
to
if(mysqli_num_rows($result) ==0){}
A good approach for increasing a count in a column is using SQL to increase that.
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = (`Num_of_downtime` + 1), `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
This way you can skip your $numdowntime calculation, and the result is more accurate.
In your current setup, two users may fire the event at the same time, they both retrieve the same number from the database (ie. 9), both increasing it with one (ie. 10), and writing the same number in the database.
Making your count one short of the actual count.
SQL takes care of this for you by locking rows, and you are left with a more accurate result using less logic :)
You miss the mysqli_query() function, which actually queries the database.
$sqlupdate = mysqli_query("
UPDATE `Test_downtime`.`Downtime`
SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now()
WHERE `Server_Name` = '$servername'"
);

SQL Syntax with Updating 2nd table on 1st table insert

I am trying to issue a mysqli_multi_query, in which my querys are named $query & $query2. Query 1 is a seperate table from query 2. This is a sample of how the code syntax looks like:
$query1 = "INSERT INTO invoices (`id`,`c`) VALUES (NULL, '$client_id')";
$query2 = "UPDATE `customers` SET `a` = `$a`,`b` = `$b` WHERE `customers.id` = $client_id";
the invoices.client_id is the same as the customers.id, and I only want to update customers.id that matches the invoice client_id.
For some odd reason, everything is updated fine into my invoices, but not into my customers. Is my syntax correct?
after our discussion in the chat we figured out the following misstakes:
Your code:
$query2 = "UPDATE customers SET alarmcode = $alarmcode, garagecode = $garagecode, gatecode = $gatecode, liason = $liason, lphone = $lphone WHERE customers.id = '$client_id'";
table-def:
So the problem was not correct encapsulating of strings in the sql statement.
corrected statement was:
$query2 = "UPDATE customers SET alarmcode = '$alarmcode', garagecode = '$garagecode', gatecode = '$gatecode', liason = '$liason', lphone = '$lphone' WHERE id = $client_id";

apostrophe causing error with row duplication of table items already run through mysqli_real_escape_string & trim

I've been successful with duplicating joined tables. Yay!
Now, after a number of tests, I've found that single apostrophe (escaped items) aren't being accepted. When originally creating new tables rows in the form, everything was run through the following:
$unit_id = mysqli_real_escape_string($dbc, trim($_POST['ajax_unit_id']));
Now, as I am duplicating these rows to create new records, I don't seem to know where/how to escape_string again in order to allow for single apostrophes again, such as a title called Don's Supah-Dupah App.
Duplication php:
$sql1 = "CREATE TEMPORARY TABLE tmp
SELECT *
FROM ".ID_TABLE."
WHERE `unit_id` = " . $id . "";
$result = mysqli_query($dbc,$sql1) or die(mysqli_error($dbc));
$sql2 = "ALTER TABLE tmp
DROP COLUMN `unit_id`";
$result = mysqli_query($dbc,$sql2) or die(mysqli_error($dbc));
$sql3 = "UPDATE tmp
SET `title` = '" . $titleStamp . "'";
# ************************************************************ #
# ****** This is where I believe the issue is occurring ****** #
# ************************************************************ #
$result = mysqli_query($dbc,$sql3) or die(mysqli_error($dbc));
$sql4 = "INSERT INTO ".ID_TABLE."
SELECT 0,tmp.*
FROM tmp";
$result = mysqli_query($dbc,$sql4) or die(mysqli_error($dbc));
$unit_id1 = $dbc->insert_id; //mysqli_insert_id($dbc); // Store new unit_id as var
$sql5 = "DROP TABLE tmp;";
$result = mysqli_query($dbc,$sql5) or die(mysqli_error($dbc));
After combing through the coding again, I found that the error actually had nothing to do with the duplication...sort of.
Note: I am providing this answer in case it helps someone out there to step back, look at there own issue from 5000m meters...instead of from 5 inches. Hopefully this helps someone to pull themselves out of the rabbit hole to get a better perspective.
Earlier before the duplication, I'd set up a variable $title that was generated by an initial sql select
$row = mysqli_fetch_array($rdata);
$title = $row['title'];
...then concatenate the title and a datetimestamp.
date_default_timezone_set(DEFAULT_TZ); // Default timezone set as Australia/Melbourne
$timestamp = date('Y/m/d h:i:s:a');
$titleStamp = $title." COPY ".$timestamp;
This $title variable is where the issue was occurring. The new string had to be escaped before the content could be inserted back into the new row.
$title = mysqli_real_escape_string($dbc, trim($row['title']));
Voila!

Insert data in current table and update another table MySQL

I'm having problem with inserting in purchase table and updating facility table. Let's say, user made a purchase with product_id and product_quantity.
The query is running. But it inserts twice with the same data and not updating facility table.
When user hit submit, I want to insert product_id and product_quantity into purchase table. And updating facility table with product_id and product_quantity that associated with it.
Here is my code
<?php
include 'dbconn.inc.php';
include 'functions.inc.php';
$sql1 = "SELECT * FROM facilities";
$res = $mysqli->query($sql1);
$facilities = array();
while( $row = $res->fetch_array(MYSQLI_ASSOC) ){
$facilities[]['id'] = $facilities_id;
$facilities[]['product_id'] = $facilities_product_id;
$facilities[]['product_current_quantity'] = $product_current_quantity;
}
$id = $mysqli->real_escape_string ($_POST['id']);
$purchase_id = $mysqli->real_escape_string( $_POST['purchase_id'] );
$facility_id = $mysqli->real_escape_string( $_POST['facility_id'] );
$product_quantity = $mysqli->real_escape_string( $_POST['product_quantity'] );
$sql1 = "UPDATE facilities
SET
`product_current_quantity` = '$product_quantity + $product_current_quantity'
WHERE $facility_id = $facilities_id AND $id = $facilities_product_id ";
$sql = "INSERT INTO purchases
(
`purchase_id`,
`facility_id`,
`product_quantity`,,
`product_id`
)
VALUES
(
'$purchase_id',
'$facility_id',
'$product_quantity',
'$id'
)";
I did some research and I think I need to use triggers. But I never work with triggers before. Any helps would be great. Thank you!
Please execute your query and better use echo statement if you have doubt in query.
use "php.net"
used this code to your updates
product_current_quantity = product_current_quantity + $product_current_quantity
how many number they can add to your product Quantity and they sum the current number.
You have used insert query and update query for the same variable $sql without any condition. If so always your following query only executes.
Then anymore no update only insertion will reflect in your table.
$sql = "INSERT INTO purchases
(
`purchase_id`,
`facility_id`,
`product_quantity`,,
`product_id`
)
VALUES
(
'$purchase_id',
'$facility_id',
'$product_quantity',
'$id'
)";

Using Update Query to Copy Column Data

I need to copy the value in a column named TEAM from one row into another row. Both rows need to have the same team name. This is my query that doesn't work:
$query = "UPDATE profiles SET team = (SELECT team FROM profiles WHERE id = '$coach_id') WHERE id = '$player_id'";
I have tried removing single quotes, removing "FROM profiles", changing value to table.value, tried to give a newdata.clan alias, and I have even tried changing the values to integers instead of parameters. Nothing works, and this is what I get:
Error: You have an error in your SQL
syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near 'WHERE id = '') WHERE id = ''' at
line 3
$query1 = "SELECT team FROM profiles WHERE id = '$coach_id'";
/* get the value of the first query and assign it to a variable like $team_name */
$query2 = "UPDATE profiles SET team = '$team_name' WHERE id = '$player_id'";
Also, you should surround your PHP variables in curly braces:
$query = "UPDATE profiles SET team = \"(SELECT team FROM profiles WHERE id = '{$coach_id}')\" WHERE id = '{$player_id}'";
From the MySQL manual:
"Currently, you cannot update a table
and select from the same table in a
subquery."
Source: http://dev.mysql.com/doc/refman/5.0/en/update.html
Use the method that FinalForm wrote:
<?
$coach_id = 2;
$player_id = 1;
$query1 = "SELECT team FROM profiles WHERE id = '$coach_id'";
$rs = mysql_query($query1);
if ($row = mysql_fetch_array($rs)) {
$team_name = $row['team'];
$query2 = "UPDATE profiles SET team = '$team_name' WHERE id = '$player_id'";
mysql_query($query2);
// Done, updated if there is an id = 1
} else {
// No id with id = 2
}
?>

Categories