php mysql insert and update - php

Hy there, I guess I've tried everything I could. Somehow my form doesn't work.
I get an ID through the URL - Which I try to use to update the MySQL table
I use the same Form also to input a new Record and there is no problem. But to update it doesn't work at all.
if (true !=$fehler)
{
if ($clientid == 'new')
{
$qy = 'INSERT INTO tbl_clientdb (
clientid,
c_update,
c_Uupdate,
c_Gender,
c_IDNumber,
c_Name,
c_Firstname,
c_Middlename,
c_idCity,
c_idCountry,
c_idLanguage,
c_Phone,
c_Cellphone,
c_Email,
c_Note,
c_idCompany
)
VALUES (
NULL,
NOW(),
"'.$c_Uupdate.'",
"'.$c_Gender.'",
"'.$c_IDNumber.'",
"'.$c_Name.'",
"'.$c_Firstname.'",
"'.$c_Middlename.'",
"'.$c_idCity.'",
"'.$c_idCountry.'",
"'.$c_idLanguage.'",
"'.$c_Phone.'",
"'.$c_Cellphone.'",
"'.$c_Email.'",
"'.$c_Note.'",
"'.$c_idCompany.'"
)';
} else {
$qy = 'UPDATE
tbl_clientdb
SET
c_update = NOW(),
c_Uupdate = "'.$c_Uupdate.'",
c_Gender = "'.$c_Gender.'",
c_IDNumber = "'.$c_IDNumber.'",
c_Name = "'.$c_Name.'",
c_Firstname = "'.$c_Firstname.'",
c_Middlename = "'.$c_Middlename.'",
c_idCity = "'.$c_idCity.'",
c_idCountry = "'.$c_idCountry.'",
c_idLanguage = "'.$c_idLanguage.'",
c_Phone = "'.$c_Phone.'",
c_Cellphone = "'.$c_Cellphone.'",
c_Email = "'.$c_Email.'",
c_Note = "'.$c_Note.'",
c_idCompany = "'.$c_idCompany.'"
WHERE
clientid = '.$clientid.'
LIMIT 1';
}
if ($res = mysql_query($qy))
{
echo 'Your data has been saved successfully';
}
else
{
echo mysql_error();
$meld = 'Please try again';
}
}`
anybody an idee what could be the trouble?
thx a lot for any inputs.

$qy = 'SELECT
clientid,
c_update,
c_Uupdate,
c_Gender,
c_IDNumber,
c_Name,
c_Firstname,
c_Middlename,
c_idCity,
c_idCountry,
c_idLanguage,
c_Phone,
c_Cellphone,
c_Email,
c_Note,
c_idCompany
FROM tablename WHERE id='$id' LIMIT 1";
$query = mysqli_query($yourConnection, $qy) or die (mysqli_error());
While ($row = mysqli_fetch_array($query)) {
/* Create a variable to hold all the data */
$c_update = $row['c_update'];
/* Do same for the rest */
}
Mysqli_free_result($query);
?>
Hope this helps

Related

how to avoid duplicate data with php

How do I avoid duplicate data when we enter the same data again? instead, I want to issue a warning:
sorry your username has been used
I'm using php script, I have done it to overcome duplicate data but the results have unexpected errors.
This is my code, please correct it if you wish. thanks
<?php
if (isset($_POST['submit'])) {
$npm_siswa = $_POST['npm_siswa'];
$nama_siswa = $_POST['nama_siswa'];
$bidangst_siswa = $_POST['bidangst_siswa'];
$ipk_siswa = $_POST['ipk_siswa'];
$query ="INSERT INTO class(npm_siswa, nama_siswa, bidangst_siswa, ipk_siswa) VALUES('$npm_siswa','$nama_siswa','$bidangst_siswa','$ipk_siswa')";
$insert_data = mysqli_query($con, $query);
$goto = header('location: input_data.php');
if (headers_sent($goto) == true) {
exit();
}
}
$checking = "SELECT * FROM class WHERE npm_siswa ='$npm_siswa'";
$process = mysqli_query($con, $checking) or die(mysqli_error());
while($row_filter = mysqli_fetch_assoc($process)) {
$kelasId = $row_filter['kelasId'];
$npm_siswa = $row_filter['npm_siswa'];
$nama_siswa = $row_filter['nama_siswa'];
$bidangst_siswa = $row_filter['bidangst_siswa'];
$ipk_siswa = $row_filter['ipk_siswa'];
}
if (mysqli_num_rows($process) > 0) {
echo "maaf nama anda sudah digunakan";
} else {
$data = "INSERT INTO class(npm_siswa, nama_siswa, bidangst_siswa, ipk_siswa) VALUES('$npm_siswa','$nama_siswa','$bidangst_siswa','$ipk_siswa')";
$check = mysqli_query($con, $data);
}
?>
The easy way is to first select rows from mysql using a select statement, and then check if the array is empty.
$checking = "SELECT * FROM class WHERE npm_siswa ='$npm_siswa'";
$process = mysqli_query($con, $checking) or die(mysqli_error());
if(empty($process)) {
echo "maaf nama anda sudah digunakan";
} else {
$data = "INSERT INTO class(npm_siswa, nama_siswa, bidangst_siswa, ipk_siswa) VALUES('$npm_siswa','$nama_siswa','$bidangst_siswa','$ipk_siswa')";
$check = mysqli_query($con, $data);
}
Another solution: make sure that it is the DBMS that controls the uniqueness, with a UNIQUE constraint. Then test your mysqli_query's return value to handle the error.
$process = mysqli_query($con, $checking);
if (!$process)
{
// Handle your error
}
Pros : Only one query
Cons : The error is not necessarily due to the UNIQUE constraint

Disable updating data when database is empty

I am having a problem when I want to echo "The stock is less than what you want". The problem is the user still can update the cart when the stock in my database less that what the user wants. It should show an error "The stock is less than what you want".
This is my code.
<?php session_start();
require("config.php");
$user = $_SESSION['userlogin'];
$cek = mysql_query("SELECT * FROM transaksitbl WHERE username = '$user' AND status ='0'") or die(mysql_error());
$result = mysql_num_rows($cek);
$data = mysql_fetch_array($cek);
if ($result > 0)
{
$faktur =$data['notransaksi'];
for ($i=1; $i<=$_POST['n']; $i++)
{
$idp = $_POST['id'.$i];
$cari2 = mysql_query("SELECT * FROM barangtbl WHERE id='$idp'") or die(mysql_error());
$row2 = mysql_fetch_array($cari2);
$har = $row2['harga'];
$stock = $row2['stock'];
if($_POST['n'] <= $row2['stock'])
{
echo "The stock is less than what you want";
}
if ($cari2)
{
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
}
}
}
header ("location:shopping_cart.php");
?>
If i understood you properly the
if($cari2){}
function is executing?
All you are checking there is if the $cari2 variable is true.
Simply make a else statement out of the if($cari2){} statement so that if the stock is less than you wan't the second if statement won't get executed.
So, like this:
if($_POST['n'] <= $row2['stock']){
echo "The stock is less than you want";
}
else {
if($scari2){
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
} else {
die('Woop, there seems to be a problem with the $scari2 variable. The value is:' . $scari2);
} // END OF INNER ELSE
} // END OF ELSE
And one more thing NEVER forget to use the mysql_real_escape_string() function on a variable before submiting it's value to the database.

Update successfully but couldn't update into DB

I couldn't find any error. I tried the query on phpmyadmin and it works well but when I do in php page, it couldn't update into DB. The following code below:
$registerID = ($_POST['registerID']);
$firstName = ucwords(htmlspecialchars($_POST['firstName']));
$lastName = ucwords(htmlspecialchars($_POST['lastName']));
$emailAddress = htmlspecialchars($_POST['emailAddress']);
$mainAddress = ucwords(htmlspecialchars($_POST['fullAddress']));
$updateCity = ucwords($_POST['userCity']);
$updateCountry = $_POST['userCountry'];
$postalCode = strtoupper(htmlspecialchars($_POST['userZip']));
$profilePic = $_POST['pic'];
$updateProf = " UPDATE register_user
SET firstName='$firstName',
lastName='$lastName',
emailAddress='$emailAddress',
mainAddress='$mainAddress',
registerCity='$updateCity',
registerCountry='$updateCountry',
postalCode='$postalCode'
WHERE registerID = '$registerID'";
if (mysqli_query($mysqli, $updateProf)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($mysqli);
}
In the end, there are no errors after I updated on the webpage, it just show Record updated successfully. But it didn't update into DB. Any ideas?
UPDATED CODING
$checkProfile = "SELECT * FROM register_user where emailAddress = '$emailAddress'";
$editProfile = mysqli_query($mysqli,$checkProfile);
if ($editProfile) {
if (mysqli_num_rows($editProfile) > 0) {
header("Location: event?error=That name of email has already been taken");
} else {
$updateQuery = "UPDATE register_user
SET firstName = '$firstName',
lastName = '$lastName',
emailAddress = '$emailAddress',
mainAddress = '$mainAddress',
registerCity = '$updateCity',
registerCountry = '$updateCountry',
postalCode = '$postalCode'
WHERE registerID = '$registerID'";
$updateResult = mysqli_query($mysqli,$updateQuery);
header("Location: profileUser");
}
}
After I updated, it still doesn't work after I am using prepared statement. Any ideas?
Try executing the query first, saving it into a variable.
then, check if the query executed by doing:
if(!$query) echo "Query error : " . $mysqli->error;
This will give you more detailed error report.

PHP Validating Submit

I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query

Create an accept or deny action to a friend system using php mysql ajax jquery

i have a friend request system that allow users to send a request to others and i have a accept or deny button . but the problem is that there is something in the code that is not write and make the system to show nothing and i do not know where is the error
can anyone help me ?????
this is the ajax part
//function for accepting freinds
function acceptFriendRequest(x){
$.post(url,{request:"acceptFriend",reqID:x,thiswipt:thisRandNum},function{data}{
$("#req"+x).html(data).show();
));
}
//function to deny friend request
function denyFriendRequest(x){
$.post(url,{request:"denyFriend",reqID:x,thiswipt:thisRandNum},function{data}{
$("#req"+x).html(data).show();
));
}
the php code:
///***************IF ACCEPT FRIEND***************//
if($_POST["request"]=="acceptFriend")
{
$reqID = preg_replace('#[^0-9]#i', '', $_POST['reqID']);
$sql = mysql_query("SELECT * FROM friend_requests WHERE id = '$reqID' LIMIT 1")or die(mysql_error());
$numRow = mysql_num_rows($sql);
if($numRow<1)
{
echo "An error occured";
exit();
}
while($row = mysql_fetch_array($sql))
{
$mem1 = $row['mem1'];
$mem2 = $row['mem2'];
}
//query for mem1 mem2 array
$sql_frnd_mem1_array = mysql_query("SELECT friend_array FROM members WHERE user_id='$mem1' LIMIT 1")or die(mysql_error());
$sql_frnd_mem2_array = mysql_query("SELECT friend_array FROM members WHERE user_id='$mem2' LIMIT 1")or die(mysql_error());
while($row = mysql_fetch_array($sql_frnd_mem1_array))
{
$frnd_array_mem1 = $row['friend_array'];
}
while($row = mysql_fetch_array($sql_frnd_mem2_array))
{
$frnd_array_mem2 = $row['friend_array'];
}
$frnArrayMem1 = explode(",",$frnd_array_mem1);
$frnArrayMem2 = explode(",", $frnd_array_mem2);
//*******************PREVENT DUPLICATION IN id**************
if(in_array($mem2,$frnArrayMem1))
{
echo "this member is already your friend!";
exit();
}
if(in_array($mem1,$frnArrayMem2))
{
echo "this member is already your friend!";
exit();
}
// puting each other in friend array field
if($frnd_array_mem1 !="" )
{
$frnd_array_mem1 ="$frnd_array_mem1, $mem2";
}
else
{
$frnd_array_mem1 = "$mem2";
}
if($frnd_array_mem2 !="" )
{
$frnd_array_mem2 ="$frnd_array_mem2, $mem1";
}
else
{
$frnd_array_mem2 = "$mem1";
}
$UpdateArrayMme1 = mysql_query("UPDATE members SET friend_array = '$frnd_array_mem1' WHERE user_id = '$mem1'") or die(mysql_error());
$UpdateArrayMme2 = mysql_query("UPDATE members SET friend_array = '$frnd_array_mem2' WHERE user_id = '$mem2'") or die(mysql_error());
$deleteThisPendingRequest =mysql_query("DELETE FROM friend_requests WHERE id = '$reqID' LIMIT 1")or die(mysql_error());
echo "you are now friend with this member!";
exit();
}
//*********deny Friend***************
if($_POST['request']=="denyFriend")
{
$reqID = preg_replace('#[^0-9]#i', '', $_POST['reqID']);
$deletethisPendigRequest = mysql_query("DELETE FROM friend_requests WHERE user_id = '$reqID' LIMIT 1 ")or die(mysql_error());
echo "Request Denied";
exit();
}
I think there is something wrong in your code :
on
//function for accepting freinds
function acceptFriendRequest(x){
$.post(url,{request:"acceptFriend",reqID:x,thiswipt:thisRandNum},function{data}{
$("#req"+x).html(data).show();
));
}
and
//function to deny friend request
function denyFriendRequest(x){
$.post(url,{request:"denyFriend",reqID:x,thiswipt:thisRandNum},function{data}{
$("#req"+x).html(data).show();
));
}
function{data}{} should be function(data){}

Categories