Why am i unable to insert a data in to data base - mysql

These are the codes for the page:
<?php
session_start();
if(isset($_SESSION['level'])){
if($_SESSION['level'] == 2 ){
require("../db/dbConn.php");
$submitted = isset($_POST['submit']);
if($submitted){
//check user's input
if(isset($_POST['issue_type'])){
$issue_type =$_POST['issue_type'];
}
else {
$issue_type = null;
echo '<p><font color="red">Please Select a Issue Type</font></p>';
}
if(isset($_POST['description'])){
$description=$_POST['description'];
}
else{
$description = null;
echo '<p><font color="red">You forgot to enter a description</font> </p>';
}
if(isset($_POST['reported_account_id'])){
$reported_account_id = $_POST['reported_account_id'];
}
else{
$reported_account_id = null;
echo '<p><font color="red">You forgot to enter your ID</font></p>';
}
if(isset($_POST['DateTimeCreated'])){
$DateTimeCreated=$_POST['DateTimeCreated'];
}
else{
$DateTimeCreated= null;
echo '<p><font color="red">You forgot to enter the date and time of the Issue </font></p>';
}
//Prepare the Insert Statement
$stmt = "INSERT INTO problem (issue_id, description, reported_account_id, DateTimeCreated) VALUES ('$issue_type', '$description','$reported_account_id','$DateTimeCreated')";
$result = mysqli_query($conn, $stmt);
$conn->close();
//TODO 5: Check result of executing insert statement and rows inserted. Print user's input if 1 row is inserted successfully,
// else print error message
if($result==true){
echo '<p><font color="green">The problem has been created. Thank you</font></p>';
echo '<p>Registration Successful Please Click Here';
} else {
echo "<p><font color=red><b>Data not saved. Please try again</b></font></p>";
echo '<p>Inserting Failed Please Click Here to Try Again';
}
}}
} else {
header("Location: ../index.php");
}
?>
I am not able to submit the insert the details from the form page into the database. That is the only issue that i am faced with. Please help me point out the errors that i made.

To Fix the issue, please replace
$stmt = "INSERT INTO problem (issue_id, description, reported_account_id, DateTimeCreated) VALUES ('$issue_type', '$description','$reported_account_id','$DateTimeCreated')";
With
$stmt = "INSERT INTO problem (issue_id, description, reported_account_id, DateTimeCreated) VALUES ('"+$issue_type+"', '"+$description+"','"+$reported_account_id+"','"+$DateTimeCreated+"')";

Related

MYSQL ON DUPLICATE KEY UPDATE not working as intended [duplicate]

This question already has answers here:
Insert into a MySQL table or update if exists
(12 answers)
Closed 2 years ago.
My app automatically checks when the customer logs in and only gives back one access_token and one shop values.
Below is the table with headings and a row of example data
access_token
shop
111111111
shop1
Sometimes a new customer installs the app and a new shop and access_token is created and I need to INSERT all new data in each column.
Other times the customer has re-installed the app so the shop exists but the access_token has changed and I need to update it.
How do I INSERT if none exist, but UPDATE if a value (shop) exists and another (access_token) doesn't when I am only given a single value of each?
I have attempted with ON DUPLICATE KEY UPDATE below where the shop is the same but the access_token has changed, but because I only get given one access_token to check when the customer logs in to the app it would just insert and not update.
INSERT INTO customers (access_token, shop)
VALUES(111, "shop1")
ON DUPLICATE KEY UPDATE access_token=111
I have attempted an example below where the shop is the same but the access_token has changed, however, I keep getting syntax errors. Please help, thank you.
SELECT EXISTS(SELECT shop FROM customers WHERE shop = 'shop1') AS sp,
NOT EXISTS (SELECT access_token FROM customers WHERE access_token = '{999999999}') AS tk
IF sp AND tk = 1
UPDATE customers
SET access_token='999999999'
WHERE shop = 'shop1';
ELSEIF NOT EXISTS (SELECT shop FROM customers WHERE shop = 'shop1') THEN
INSERT INTO customers (access_token, shop)
SELECT * FROM (SELECT '999999999', 'shop1') AS tmp;
END IF;
Are you using purely MySQL? I have made a signup and login page before as part of a web app and used Php to do this. I believe you can use Php for apks so I will write in Php, but you should be able to translate to your language with ease.
<?php
if (isset($_POST['signup-submit'])) { //this is so that the following can only be done on
the button press (name of it is signup-submit)
require 'dbh.inc.php';
$username = $_POST['Username'];
$email = $_POST['mail'];
$password = $_POST['pwd'];
$confirmpassword = $_POST['cpwd']; //this is all off the details of the user passed
through to be run through this script into the
database
if (empty($username) || empty($email) || empty($password) || empty($confirmpassword)) {
header("Location: ../index.php?error=emptyfields&uid=". $username. "&mail=". $email);
exit();
} //checking for empty fields
else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9 ]*$/", $username)) {
header("Location: ../index.php?error=invalidemail&uid");
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../index.php?error=invalidemailuid");
exit();
}
else if (!preg_match("/^[a-zA-Z0-9 ]*$/", $username)) {
header("Location: ../index.php?error=invaliduid&email=". $email);
exit();
}
else if ($password !== $confirmpassword) {
header("Location: ../index.php?error=checkpasswords&mail=".$email. "&uid=".$username);
exit();
} //checking all characters used are only that which you allow
else {
$sql = "SELECT uidusers FROM users WHERE uidusers=?";
$sqly = "SELECT emailusers FROM users WHERE emailusers=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
} //using prepared statements to insert user info
else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../index.php?error=usertaken&mail=". $email);
exit();
} //checking for existing details
if (!mysqli_stmt_prepare($stmt, $sqlx)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
if (!mysqli_stmt_prepare($stmt, $sqly)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck3 = mysqli_stmt_num_rows($stmt);
if ($resultCheck3 > 0) {
header("Location: ../index.php?error=emailtaken");
exit();
} //storing details
else {
$sql = "INSERT INTO users (uidusers, emailusers,
pwdusers, invcode) VALUES (?, ?, ?, ?) ";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else {
$hashedpwd = password_hash($password, PASSWORD_DEFAULT); //hashing passwords
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedpwd);
mysqli_stmt_execute($stmt);
header("Location: ../index.php?signup=success"); //all details stored successfully
As for your access token, I would suggest adding a function to run a uniqid() function along with another function to check for existing tokens so that duplicates aren't made ( I did this for another similar reason to yours) and then using similar code as above to write that in.
I'm not sure what your shop ID is for but I have options for 2 eventualities:
If it's just a sort of ID, auto increment it in the database
If it's to show which shop the person entered, use foreign keys to link the column to a parent table with all the shops listed and set the relationship to cascade. Then make a button to switch shops that will
A) send an update to the database, overwriting the child column and row of the user
B) redirect the user to the new shop
(I have no idea why the second half of the code is green, but if you remove my comments you should be good, though I'd advise you to write your own code so that you can see how it works and adapt it to your own project)

Getting comments from mysql

I am just wondering where my mistake was , and if it is a simple fix or if it will be a bit harder to fix. You guys don't have to write the answers for me, just point me in the right direction and I think I should be fine, because I've been looking at this for half an hour now , and I can't seem to figure out where my mistake was..
Inserting comments is working wonderfully, I'm just having issues with getting them, and posting them on my page(?)
// INSERTING COMMENTS INTO THE DATABASE
<?php
function setComments($conn) {
if (isset($_POST['commentSubmit'])) {
$author = $_POST['cauthor'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (c_author, c_date, c_message)
VALUES ('$author', '$date', '$message')";
$result = mysqli_query($conn, $sql);
}
} ?>
// GETTING COMMENTS FROM THE DATABSE
<?php
function getComments($conn) {
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn, $sql);
$row = $result->fetch_assoc();
echo "$row['c_message']";
}
?>

Strange behaviour of preg_replace and sql select

preg_match_all('#\<td id=\"(.*)\" class=\"(.*)column(.*)\>(.*)\<\/td\>#i', $htmlcontent, $matches);
$output = $htmlcontent;
foreach ($matches[1] as $match) {
echo $match.",";
$ressql = "SELECT * FROM var WHERE varimportedindex = '".$match."' AND projectid = '".$pid."' AND sheetName = '".$sheetName."'";
$result2 = $db->query("SELECT * FROM var WHERE varimportedindex = '".$match."' AND projectid = '".$pid."' AND sheetName = '".$sheetName."'");
$rowoperation = $result2->fetch_assoc(); //<-- HERE
#echo $rowvalue = $rowoperation['varvalue'];
$output = preg_replace("#\<td id=\"(.*)\" class=\"(.*)column(.*)\>(.*)\<\/td\>#i", "<td id='\\1' class=\"\\2column\\3\"><input type='input' id='\\1' name='\\1' value='".$rowvalue."'>\\4</td>", $output);
}
echo $output;
Ok, i can not find PROBLEM there, but if i deactivate replacement row HERE everything works fine. But when i activate it, replacement is not working anymore.
Can someone find the problem with these lines?
Thank you so much.
Regards,
Olaf
// Olaf, please edit your question to display a sample input value for $htmlcontent
if(!preg_match_all('#\<td id=\"(.*)\" class=\"(.*)column(.*)\>(.*)\<\/td\>#i',$htmlcontent,$matches)){
echo "<div>No match</div>";
}else{
$where_ext=implode("' OR `varimportedindex`='",$matches[1]);
$query="SELECT * FROM `var` WHERE projectid='{$pid}' AND `sheetName`='{$sheetName}' AND (`varimportedindex`='{$where_ext}') ORDER BY varimportedindex;"; // only run one query
if($result=$db->query($query)){
$pattern="#\<td id=\"(.*)\" class=\"(.*)column(.*)\>(.*)\<\/td\>#i";
while($row=$result->fetch_assoc()){
echo "<div>vii={$varimportedindex} & vv={$row["varvalue"]}</div>";
// Olaf, please state what $varvalue's value might be
$replace="<td id='\\1' class=\"\\2column\\3\"><input type='input' id='\\1' name='\\1' value='{$row["varvalue"]}'>\\4</td>";
$output=preg_replace($pattern,$replace,$output);
}
echo "<div>{$output}</div>";
// Olaf, please edit your question to display your expected result based on your sample $htmlcontent
}else{
echo "<div>{$db->error}</div>";
}
}

delete user from table

I have this table where I want to delete user from. The users are in my database "login" where they have an id, username and password.
"Id" is the primary key, I want to delete the user where I click in my table
Hope you can help me out!
<?php
$account = '<font size="4">'.$account.'</font>';
$password1 = 'Password:';
$password1 = '<font size="4">'.$password1.'</font>';
//check db connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Take everything from table and fill in $result
$sql = "SELECT * FROM login";
$result = $conn->query($sql);
echo"<table border=4><tr><td>$account</td><td>$password1</td><td>Action</td></tr>";
if ($result->num_rows > 0) {
// Take all data
while($row = $result->fetch_assoc()) {
echo"<tr><td>".$row['username']."</td><td>".$row['password']."</td><td> edit | delete </td></tr>";
}
} else {
// nothing in DB is 0 results
echo "0 results";
}
echo"</table>";
$conn->close();
?>
<td> edit | <a href='baseURL/deleteUser.php&id=$userId'> delete</a> </td></tr>";
create a page deleteuser.php, get the id via $_GET['id'] and delete accordingly.
This is a very crude approach to delete users and the id goes via browser url. You can add forms here and delete text can be a submit button .. The id can be sent as hidden and obtained via $_POST

mysql_fetch_array fails sometimes

I'm trying to implement the connection to a online payment framework.
One of the files is giving me some trouble, because sometimes the code works, sometimes it doesn't... And I can't understand why...
Here's where the code is failing...
$sql = "select transidmerchant,totalamount from nsiapay where transidmerchant='".$order_number."'and trxstatus='Verified'";
$result = mysql_query($sql);
**$checkout = mysql_fetch_array($result);**
echo "sql : ".$sql;
$hasil=$checkout['transidmerchant'];
echo "hasil: ".$hasil;
$amount=$checkout['totalamount'];
echo "amount: ".$amount;
// Custom Field
if (!$hasil) {
echo 'Stop1';
} else {
if ($status=="Success") {}
}
It's just part of the code but I think it's enough for you to try to see the problem... It fails on the bold line, $checkout = mysql_fetch_array($result);
The weird thing is that the "echo sql" works, and it shows the right values, but then when I put them on the array, sometimes the variables are passed, sometimes they're not... And so, when getting to if (!$hasil) it fails because the value is empty... but sometimes it works...
Any ideas on what might be happen?
Thans
Luis
The only way this fail is when query doesn't return anything.
The correct way would be to check if there is something returned:
$sql = "select transidmerchant,totalamount from nsiapay where transidmerchant='".$order_number."'and trxstatus='Verified'";
$result = mysql_query($sql);
if($checkout = mysql_fetch_array($result)){
$hasil = $checkout['transidmerchant'];
echo "hasil: ".$hasil;
$amount=$checkout['totalamount'];
echo "amount: ".$amount;
// Custom Field
if (!$hasil) {
echo 'Stop1';
} else {
if ($status=="Success") {}
}
}else{
echo "Empty query result";
}