Insert and update into different tables in one Mysql query in php - php

I've tried the code below but it didn't work:
if (isset($_POST['ubah'])) {
$queryUpdate = mysqli_multi_query("INSERT INTO perbaikan SET id_perbaikan = '',idrusakbaik = '" . $id . "',komenrusak = '" . $_POST['komenrusak'] . "',tglbaik = '" . $tgl_sekarang . "'; UPDATE kerusakan SET status = '" . $_POST['status'] . "'WHERE id_kerusakan = '" . $id . "'");
if ($queryUpdate) {
echo "<script> alert('Data Berhasil Disimpan'); location.href='index.php?hal=master/perbaikan-mekanik/list' </script>";
exit;
}
}

There is no such thing as "two queries in one query". There are always two queries. and there is not a single reason to run them in one call. therefore just rewrite your query to two prepared statements
$sql = "INSERT INTO perbaikan SET id_perbaikan = '',idrusakbaik = ?,komenrusak = ?,tglbaik = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $id, $_POST['komenrusak'],$tgl_sekarang);
$stmt->execute();
$sql = "UPDATE kerusakan SET status = ? WHERE id_kerusakan = ?");
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $_POST['status'], $id);
$stmt->execute();

Related

Cannot update the row in mysql via php

I tried to update a row in table showtable
Bugupdate
By using the php code below, binding a bugID to a SQL UPDATE statement to update the row I want to but it doesn't seem to work, is it the problem lie in my SQL statement ?
$id = $_GET['update'];
$games = htmlentities($_POST['games']);
$version = htmlentities($_POST['version']);
$platform = htmlentities($_POST['platform']);
$frequency = htmlentities($_POST['frequency']);
$proposal = htmlentities($_POST['proposal']);
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?,Platform=?,Frequency=?,Proposed solution=? WHERE BugID= " .$id;
if ($stmt = mysqli_prepare($DBconnect, $SQLstring2)) {
mysqli_stmt_bind_param($stmt,'sssss', $games, $version, $platform, $frequency, $proposal);
$QueryResult2 = mysqli_stmt_execute($stmt);
if ($QueryResult2 === FALSE) {
echo "<p>Unable to execute the query.</p>"
. "<p>Error code "
. mysqli_errno($DBconnect)
. ": "
. mysqli_error($DBconnect)
. "</p>";
} else {
echo "<h1> Thank you for your contribution";
}
mysqli_stmt_close($stmt);
}
mysqli_close($DBconnect);
Try to rename Proposed solution column to Proposed_solution and adapte the sql query like this :
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?, Platform=?, Frequency=?, Proposed_solution=? WHERE BugID= " .$id;

PDO Statements aren't being submitted to database

I'm fairly new to using PDO, and I'm attempting to migrate some of my websites from mysql_* to it.
I have formed the following:
if ($userData) {
$query = "SELECT * FROM table WHERE user_id = " . $db->quote($userData['id']);
$result = $db->query($query);
if ($result) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($result->rowCount > 1) {
$sql = "DELETE FROM tokens WHERE `user_id` = " . $db->quote($userData['id']) . "' AND `id` != '" . $row['id'];
$stmt = $db->prepare($sql);
$stmt->execute();
}
}
if (!$row) {
$sql = "INSERT INTO tokens SET `user_id` = " . $db->quote($userData['id']) . "', `name` = '" . $db->quote($userData['name']) . "',`access_token` = '" . $db->quote($token) . "',`alive` ='Y'";
$stmt = $db->prepare($sql);
$stmt->execute();
} else {
$sql = "UPDATE tokens SET `access_token` = " . $db->quote($token) . "' WHERE `id` = " . $row['id'] . "";
$stmt = $db->prepare($sql);
$stmt->execute();
}
}
}
$userData is a Facebook API variable.
The snippet above looks fine to me, but when I run through it on a live website, the information isn't added to the database.
How would I fix this? Any assistance would be greatly appreciated.
You're missing a single quote
$sql = "INSERT INTO tokens SET `user_id` = <<HERE>>" . $db->quote($userData['id']) . "', `name` = '" . $db->quote($userData['name']) . "',`access_token` = '" . $db->quote($token) . "',`alive` ='Y'";
should be:
$sql = "INSERT INTO tokens SET `user_id` = '" . $db->quote($userData['id']) . "', `name` = '" . $db->quote($userData['name']) . "',`access_token` = '" . $db->quote($token) . "',`alive` ='Y'";
And on the update statement in the same place.
Ok I am going to tell you one thing, please use placeholders. I have also been through the same problem which you are in right now. mysql_ functions are deprecated and hence developers have to use PDO or mysqli_ functions.
Please check the code and see if it works
<?php
if($userData) {
$query = "SELECT * FROM table WHERE user_id = :user_id";
$result = $db->prepare($query);
$result->execute(array(':user_id' => $userData['id']));
if ($result) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($result->rowCount > 1) {
$sql = "DELETE FROM tokens WHERE `user_id` = :user_id AND `id` != :id";
$stmt = $db->prepare($sql);
$stmt->execute(array(':user_id' => $userData['id'], ':id' => $row['id']));
}
}
if(!$row) {
$sql = "INSERT INTO tokens SET `user_id` = :user_id, `name` = :name,`access_token` = :access_token ,`alive` ='Y'";
$stmt = $db->prepare($sql);
$stmt->execute(array(':user_id' => $userData['id'], ':name' => $userData['name'], ':access_token' => $token));
} else {
$sql = "UPDATE tokens SET `access_token` = :access_token WHERE `id` = :id";
$stmt = $db->prepare($sql);
$stmt->execute(array(':access_token' => $token, ':id' => $row['id']));
}
}
}
?>

Selecting an auto_increment field returns blank In php

I am working on a php script that stores message ids (Msg_ID, Ref_ID) in their corresponding user account tables.
What I've is, the Msg_ID is properly written, but the Ref_ID is always blank.
How ever when I run the query separately it works, but doesn't work in the script for some odd reason.
Here is the code :
$qry = "SELECT Ref_ID FROM Chat WHERE Msg_ID = " .$MsgID. ")";
$resp = mysqli_query($con, $qry);
$xx = mysqli_fetch_array($resp);
$ref_id = $xx['Ref_ID'];
foreach ($Array as $user){
$query = "Insert into ".$user."(POST_ID, REF_ID) values ('". $MsgID . "', '" .$ref_id. "')";
mysqli_query($con, $query);
}
The $ref_id is always blank and as a result, the blank value is written to the respective database.
Some help with what is wrong will be helpful.
Here is the full code :
<?php
function PostMainThread($Heading, $Message, $Author, $MarkedList){
$con=mysqli_connect("mysql.serversfree.com", "u521497173_root", "123456", "u521497123_mydb");
$Array = explode(',', $MarkedList);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = "Connection Failed.";
echo json_encode($response);
}else{
here:$MsgID = rand(1, 9999999);
$query = "Insert into Chat(Msg_ID, Header, MsgBody, Author) values (". $MsgID . "," . "'" . $Heading . "' ," .
"'" . $Message . "', '". $Author . "')";
$result=mysqli_query($con, $query);
if (!$result){
goto here;
}else{
//Put the MsgID in the respective user tables.
$qry = "SELECT Ref_ID FROM Chat WHERE Msg_ID = " .$MsgID. ")";
$resp = mysqli_query($con, $qry);
$xx = mysqli_fetch_array($resp);
$ref_id = $xx['Ref_ID'];
foreach ($Array as $user){
$query = "Insert into ".$user."(POST_ID, REF_ID) values ('". $MsgID . "', '" .$ref_id. "')";
mysqli_query($con, $query);
}
$response["success"] = 1;
$response["message"] = "Submission successful.";
mysqli_close($con);
echo json_encode($response);
}
}
}
function PostReplyToThread($PostID, $Author, $Reply){
$con=mysqli_connect("mysql.serversfree.com", "u521497123_root", "123456", "u521497123_mydb");
if (mysqli_connect_errno()){
echo 2;
}else{
$query = "Insert into Chat(Msg_ID, Header, MsgBody, Author) values (". $PostID . "," . "'" . " " . "' ," .
"'" . $Reply . "', '". $Author . "')";
$result=mysqli_query($con, $query);
if ($result){
echo 3;
}else{
echo 4;
}
mysqli_close($con);
}
}
if (isset($_POST['what_to_do'])){
if ($_POST['what_to_do'] == 0){
if ((isset($_POST['Title'])) &&(isset($_POST['Body']))&&(isset($_POST['Marked']))&&(isset($_POST['_Author']))){
PostMainThread($_POST['Title'], $_POST['Body'], $_POST['_Author'], $_POST['Marked']);
}
}else if ($_POST['what_to_do'] == 1){
if ((isset($_POST['Thread_ID'])) &&(isset($_POST['Answer']))&&(isset($_POST['_Author']))){
PostReplyToThread($_POST['Thread_ID'], $_POST['_Author'], $_POST['Answer']);
}
}
}else{
$response["success"] = 0;
$response["message"] = "Unspecified action";
echo json_encode($response);
}
Definition of the Chat table :
Create table Chat(Ref_ID INT Auto_Increment, Msg_ID INT, Header varchar(50), MsgBody varchar(500
), Author varchar(30), Primary Key(Ref_ID, Msg_ID));
$xx = mysqli_fetch_array($resp);
Will only return a numerically indexed array, as in $xx[0], $xx[1].
To use the column names, you need to use:
$xx = mysqli_fetch_array($resp, MYSQLI_ASSOC);
Or the shorter version:
$xx = mysqli_fetch_assoc($resp);
As a side note, don't forget security, when inserting data that comes from outside the function and could possibly have a quotes or SQL, it needs to be escaped!
$Heading = mysqli_real_escape_string($con, $Heading);
Otherwise it will come back to bite you.

How to prevent data being sent to the database if fields are empty?

How would I go about not sending the data to the database if the some of the fields are left empty? Right as of now, if a field is empty on the form, the database is replacing whatever was in the field with blank data
UPDATE: Forgot to mention, it doesn't matter if the some of the fields are left blank, that should be allowed.
My code
<?php
if (isset($_POST['eventname'], $_POST['date'], $_POST['eventvenue'] , $_POST['eventtime'], $_POST['eventcost'])){
$eventname = ($_POST['eventname']);
$eventdate = ($_POST['date']);
$eventtime = ($_POST['eventtime']) . ":00";
$eventvenue = ($_POST['eventvenue']);
$eventcost = ($_POST['eventcost']);
$result = mysql_query("UPDATE event set event_name = '" . $eventname . "', event_date = '" . $eventdate . "', event_time = '" . $eventtime . "', event_venue = '" . $eventvenue ."', event_cost = '" . $eventcost ."'");
}
?>
Try some thing like This
$query= "UPDATE event set ":
If(isset($var1)){
$query.= " var1=".$var1;
}else if (isset($var2)){
$query.= " var2=".$var2;
}
and so forth and then
$result = mysql_query($query);
You can read on PHP's function empty()
empty() on PHP.net
Example usage:
if(empty($eventname))
{
echo "You have not set event name";
} else {
mysqli_query(...);
}
As said on comments, do not use the deprecated mysql_* functions, use either mysqli_* or PDO.
This is an example using prepared statements; it builds the update statement based on whether the field is empty (zero length) or not.
Afterwards, the prepared statement is executed.
$updates = [];
$parameters = [];
if (strlen($_POST['eventname'])) {
$updates[] = 'event_name = ?';
$parameters[] = $_POST['eventname'];
}
// ...
if (strlen($_POST['eventtime'])) {
$updates[] = "event_time = ?";
$parameters[] = $_POST[$field] . ':00';
}
if ($updates) {
$sql = sprintf('UPDATE event SET %s WHERE xxx', join(',', $updates));
$stmt = $db->prepare($sql);
$stmt->execute($parameters);
}

Is it possible to add multiple rows in one field in a database using MySQL?

So my problem is that I want to add multiple members in one team, but I cannot seem to figure out how or whether if it is even possible to do so. Here is my code for you to get my question.
<?php
$tname = $_POST['tname'];
$maxnum = $_POST['maxnum'];
$host = "localhost";
$sqluname = "root";
$sqlpass = "";
$db = "teams";
$tablename = "team info";
$mem1 = $_POST['mem1'];
$mem2 = $_POST['mem2'];
$mem3 = $_POST['mem3'];
$mem4 = $_POST['mem4'];
$connect = mysqli_connect("$host","$sqluname","$sqlpass","$db") ;
if(mysqli_connect_errno())
{
echo "Problem". mysqli_connect_error();
}
$sql = "INSERT INTO teaminfo (TeamName,MaxNum,Members)
VALUES
('$tname','$maxnum','$mem1')";
/* Inside Members, I would like to add more than just $mem1, like $mem2, $mem3, $mem4.
*/
if(!mysqli_query($connect,$sql)){
die('Error: ' .mysqli_error($connect));
}
echo "Team is added";
mysqli_close($connect);
header("location: TeamDummyClient.html");
?>
$sql = "INSERT INTO teaminfo (TeamName,MaxNum,Members) VALUES";
$sql .= "('$tname','$maxnum','$mem1'),";
$sql .= "('$tname','$maxnum','$mem2'),";
$sql .= "('$tname','$maxnum','$mem3'),";
$sql .= "('$tname','$maxnum','$mem4')";
You should be escaping the strings before you insert their values to prevent SQL injections. Here's an example for one of the rows:
$sql .= "(
'" . mysqli_real_escape_string($tname) . "',
'" . mysqli_real_escape_string($maxnum) . "',
'" . mysqli_real_escape_string($mem1) . "'
),";

Categories