Mysql does't insert query using php - php

This could sound stupid (maybe because it is) but I'm having so much problem in an insert query, this is the thing, I have in my first page a query that inserts into a table, the problem is that in my page2, I have EXACTLY the same query, but in this page doesn't work, the weirdest thing is that I echoed a message in the true statement of the query and it echoes, meaning that the query supposedly is already made, but is not, because when I check into the DB, is not there, and other thing! if I want to update the values, it works!, but not in create, I don't know why, but is bothering me a lot!, if someone could help me i really would appreciated, thanks.
Here is the code:
if($radio==2){
echo $_SESSION["in"];
$sqlb = "SELECT * FROM table WHERE idus='$idus';";
$resb = mysqli_query($con, $sqlb);
$res_b = mysqli_fetch_array($resb);
if( !$res_b) {//if not exist on table, create
$sqly="INSERT INTO table (x,y,z)
VALUES ('$x','$y','$z');";
if ($con->query($sqly) === TRUE) {
$_SESSION["in"]=1;
} else {
echo "Error: " . $sqly . "<br>" . $con->error;
}
}else{ //update if exist on table
$sqly="UPDATE table
SET y='$y',z='$z'
WHERE idus='$idus';";
if ($con->query($sqly) === TRUE) {
} else {
echo "Error: " . $sqly . "<br>" . $con->error;
}
}
header('Location: page2.php');
}
The weird thing of all is that passes through true when doing the query and do nothing, also when pasting the exact same query directly into the DB, it works.

It's hard to tell because we can't see all the code, but I think you should replace these lines, using as a reference the update query a few lines below:
$sqly="INSERT INTO table (x,y,z)
VALUES (x,y,z);";
To:
$sqly="INSERT INTO table (x,y,z)
VALUES ('$x','$y','$z');";
An explanation: x, y and z are not defined as SQL variables, but in another query below you use them as php variables, so I updated the code putting them as they should. Hope it helps.

Check your column names and properties carefully. may be x column is something wrong if update which have y,z is working fine.

I did not understand the question correctly but by looking at your code. You could achieve same behaviour by using INSERT...ON DUPLICATE query. see more here
if($radio==2){
echo $_SESSION["in"];
$sqlb = 'INSERT INTO table (x,y,z) VALUES ($x, $y, $z) ON DUPLICATE KEY UPDATE x=$x, y=$y, z=$z';
if ($con->query($sqlb) === TRUE) {
$_SESSION["in"]=1;
} else {
echo "Error: " . $sqlb . "<br>" . $con->error;
}
header('Location: page2.php');
}

Check the variables $x ,$y, $z variables .
If its is not empty then your code works otherwise insertion don't work

I don't know what actually was the problem, but I fix it by deleting all my DB structure and re do it again, thanks for all your help!

Related

how to substract two value on the column and show in another column mysql

am new to php and mysql so please dont downvote my question. i have database that takes input from html form and i need one column named KIASI_KILICHOBAKI to be inserted automatically the substraction of two column named KIASI_ALICHOUZIWA - KIASI_ALICHOTOA. these are my codes:
$KIASI_ALICHOUZIWA = $mysqli->real_escape_string($_REQUEST['KIASI_ALICHOUZIWA']);
$KIASI_ALICHOTOA = $mysqli->real_escape_string($_REQUEST['KIASI_ALICHOTOA']);
// Attempt insert query execution
$sql = ("INSERT INTO taarifa (TAREHE,JINA_LA_KWANZA, JINA_LA_MWISHO, NAMBA_YA_SIMU, SHINGO, BEGA, KIFUA, TUMBO, UPANA_WA_MKONO, UREFU_WA_MKONO, HIPS_YA_KOTI, CHINI_UPANA_MKONO, HIPS_SURUALI, PAJA, KIUNO, GOTI, UREFU_WA_SURUALI,CHINI_UPANA_SURUALI, ROUND_SURUALI, UREFU_WA_KIZIBAO, NAFASI_YA_KIZIBAO, HIPS_YA_KIZIBAO, UREFU_WA_MKONO_KIZIBAO , ROUND_YA_MKONO_KIZIBAO, KIASI_ALICHOUZIWA, KIASI_ALICHOTOA, KIASI_KILICHOBAKI) VALUES ('$TAREHE', '$JINA_LA_KWANZA', '$JINA_LA_MWISHO', '$NAMBA_YA_SIMU', '$SHINGO', '$BEGA', '$KIFUA', '$TUMBO', '$UPANA_WA_MKONO','$UREFU_WA_MKONO','$KOTI', '$CHINI_UPANA_MKONO', '$SURUALI', '$PAJA', '$KIUNO', '$GOTI' ,'$UREFU_WA_SURUALI', '$CHINI_UPANA_SURUALI', '$ROUND_SURUALI', '$UREFU_WA_KIZIBAO' , '$NAFASI_YA_KIZIBAO', '$HIPS_YA_KIZIBAO' , '$UREFU_WA_MKONO_KIZIBAO' ,'$ROUND_YA_MKONO_KIZIBAO' , '$KIASI_ALICHOUZIWA' , '$KIASI_ALICHOTOA' , '$KIASI_KILICHOBAKI')");
if($mysqli->query($sql) === true){
header('Location: http://127.0.0.1/dashboard/myindex.php');
} else{
echo "ERROR: Could not be able to execute $sql. " . $mysqli->error;
}
// Close connection
$mysqli->close();
?>
you have not created the $KIASI_KILICHOBAKI variable to save the answer. Add the following code before insert query
$KIASI_KILICHOBAKI = $KIASI_ALICHOUZIWA - $KIASI_ALICHOTOA;

PHP sql database, inserting UNIQUE values

Im working with sql database (phpMyadmin) and with programming language PHP.
I've got a table with data e.g:
T1:
145
138.8
110.6
1759.4
1400.9
1891.4
1755.4
1760.4
T2:
141.9
110.6
1400.9
1891.4
1758.4
My question >
Is there existing sql syntax, that is able to average values which are lying in ONE THRESHOLD (like > 1755.4,1760.4,1759.4 OR 145,138.8) and INSERT THEM AS UNIQUE VALUES to another table ?
What I need is create T2(contain UNIQUE values) from T1, and INSERTING them only if they didn't exist in T2.
I was trying, to looping throw 2 arrays (1starray = T1 and 2ndarray = T2 ) too. And compare data in array1 and array2, and trying to insert values which can be unique.
for($z = 0; $z<$numberApp; $z++) {
while($j<$numberAbs-1){
$Abs=$arrayabs[$j];
$state_change = (abs($Abs - abs($previous_Abs)));
if ($state_change>100){
$instantChange = True;
echo "<br>"." better than tolerance: " . $instantChange;
}
else {
$instantChange = False;
echo "<br>"." lower than tolerance" . $instantChange;
}
//if($state_change = (abs($some_item - $previous_item)<= $tolerance)){
if($Abs != $previous_Abs){
echo "<br>" ." some_item : " .$Abs." previous_item : " .$previous_Abs;
}
//$lastAbs=$arrayabs[$j];
//echo " next_item : " .$lastAbs;
if ($instantChange == True and $onChange == False){
$Abs2 [] = $podiel;
$finalPower = $podiel;
}
if ($instantChange){
$D=0;
echo "ABSOLUT >>> " .$lastAbs;
$percentual1 = ($power_app[$z] * 0.9);
$percentual2 = ($power_app[$z] * 1.1);
if(($lastAbs<$percentual1 || $lastAbs>$percentual2)){
$user = 'root';
$pass = 'password';
$db = 'vypis';
//if($N>0){
$db = new mysqli('localhost', $user, $pass, $db) or die();
$sql = "INSERT INTO vypis.nilm_app2(power) VALUES ('$lastAbs')";
if(mysqli_query($db, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
}
//$power_app[$z++];
}
Thank you for everyone, who going to help, and sorry for my bad english.
The math here sounds complex enough that you're probably better off doing the complex stuff (averaging the values and determining whether a value is unique) in PHP, then finishing off with a couple simple MySQL statements.
This can probably be done in pure MySQL with a bit of trickery, but frequently it isn't worth the time and complexity it creates. (Imagine you'll have to debug that monster SQL query six months from now!)
By contrast, it's trivial to take a handful of values in PHP and average them; it's also trivial to run a quick MySQL query to determine whether a value is unique. So if you're unsure how to mash these together into one big SQL statement, start out by just handling them in the PHP code as separate steps! Then later on, if performance issues come up, you can think about how to combine them (but at least by that point you already have something that works).

MySQL UPDATE function refuses to update database

I've been trying to make this code work for hours now but I can't seem to find solution. I've serached all relevant topics and tried to change the code, punctuation etc. but none of them worked for me.
The result is always "Success!" but the database update never works (checked in phpmyadmin).
I hope that you can find the error. The code is the following:
if(empty($_POST['nev']) || empty($_POST['orszag']) || empty($_POST['telefonszam']) || empty($_POST['iranyitoszam'])
|| empty($_POST['megye']) || empty($_POST['varos']) || empty($_POST['utca'])) {
echo "Failure! Missing data...";
}
else {
$nev = mysql_real_escape_string($_POST['nev']);
$orszag = mysql_real_escape_string($_POST['orszag']);
$telefonszamm = mysql_real_escape_string($_POST['telefonszam']);
$iranyitoszam = mysql_real_escape_string($_POST['iranyitoszam']);
$megye = mysql_real_escape_string($_POST['megye']);
$varos = mysql_real_escape_string($_POST['varos']);
$utca = mysql_real_escape_string($_POST['utca']);
$shipping_query = mysql_query("UPDATE users
SET Name=".$nev.", Phone=".$telefonszam.",
Country=".$orszag.", State=".$megye.",
City=".$varos.", ZIP=".$iranyitoszam.",
Road=".$utca."
WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'");
echo "Success!";
}
Thank you for your help!
You're missing quotes around the strings in your query.
$shipping_query = mysql_query("UPDATE users
SET Name='".$nev."', Phone='".$telefonszam."',
Country='".$orszag."', State='".$megye."',
City='".$varos."', ZIP='".$iranyitoszam."',
Road='".$utca."'
WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'");
You also no error checking on your query. So whether it succeeds or fails it will always say, "success". You need to check to see if there is a MySQL error ir rows updated before you can declare success.
Name, Phone, Country etc etc seam like VARCHARs. so, it should be treated as a string.
So, query should be like.
"UPDATE users SET Name='".$nev."', Phone='".$telefonszam."',Country='".$orszag."', State='".$megye."',City='".$varos."', ZIP='".$iranyitoszam."',Road='".$utca."' WHERE EmailAddress='" . $_SESSION['EmailAddress'] . "'"
As other answers have pointed out, you're missing quotes around your string variables.
When you're MySQL queries are failing to execute, try echoing your queries while debugging to see what exactly you're sending to the database.
$myValue = "Green";
$mySQL = "UPDATE MyTable SET MyColor = " . $myValue;
$myQuery = mysql_query($mySQL);
echo $mySQL;
Spotting the error visually is much easier when the entire SQL string is assembled in one piece.
You can also copy the assembled SQL string and paste it straight into a phpmyadmin query to get debugging information from it.

PHP MySQL INSERT query no longer works (was working yesterday)

I have a problem with an INSERT query.
Here is the problem:
Yesterday I was using this code to upload data, it was working fine. Today, when I hit submit on the form, it just shows a blank page. No errors, just blank. Nothing in the error log. All SELECT queries are working fine, so the SELECT Count(id) query still works.
Here is what I have tried:
Re-uploading to server
syntax adjustments eg '".$v.'" instead of '$v'
adding print lines to check that none of the variables are null. All is okay, all data is present just before the INSERT query.
Test insert via PHP my admin, all okay
The function call is correct - it is and remains unchanged from Yesterday
The function takes a list of species, a family and a genus, then adds them to the database.
Here is the code (the un-santised version - both were working yesterday):
error_reporting(E_ALL);
ini_set('display_errors', '1');
function submit($family, $genus, $species){
//require statement
require 'databaseConnect.php';
//get num of species
if(!($result = mysql_query("SELECT Count(id) as num FROM speciesList", $connection))) mysql_error();
$nums = mysql_fetch_row($result);
$num=$nums[0];
//parse species
$holder="";
$array = Array();
while(strlen($species)!=0){
if($species[0]==';'){
$array[] = $holder;
$holder="";
}else{
$holder = $holder . $species[0];
}
$species=substr($species, 1);
}
foreach($array as $v){
$num++;
if(!(mysql_query("INSERT INTO speciesList VALUES($num, '$family', '$genus', '.$v')", $connection))){
mysql_error();
}else{
print "success ";
}
}
mysql_close($connection);
}
Thank you very much in advance, this problem is rather mysterious to me!
Em
You never ever want to use string replacement with parameters to build SQL statements as it leaves you vulnerable to SQL injection attacks. Instead, bind your parameters.
Your code isn't returning an error because you call mysql_error() and ignore the return value. It returns the error string, so you want your code to be more like this:
if(!(mysql_query("INSERT INTO speciesList VALUES($num, '$family', '$genus', '.$v')", $connection))){
print_r( mysql_error() );
}else{
print "success ";
}
If you need help understanding the error once you see it, please post it here.
if(!(mysql_query("INSERT INTO speciesList VALUES($num, '$family', '$genus', '.$v')", $connection))){
echo mysql_error();
}else{
There maybe other things that are amiss, but the mysql_error() function returns a string. Your script needs to take some action to display the string.
I find that a better way of doing this is to construct the variables separately, so they can be displayed. And I'm not sure you want that dot before $v. See if this makes sense to you.
foreach($array as $v)
{
$num++;
$sql = "INSERT INTO speciesList VALUES($num, '$family', '$genus', '$v')";
$res = mysql_query($sql);
if (!$res) die("FAIL: $sql BECAUSE: " . mysql_error());
echo "<br/>SUCCESS: $sql";
}

data is not entering into mysql

i have written few codes to show time spent by users at site but when a users click on submit it should be stored in mysql but its not getting stored can you please tell where i have done mistake here is my code.
Your query seems to be wrong.
Either use INSERT without WHERE if you want to insert a new record. If however you want to update an already present record, use UPDATE instead of INSERT.
And it is always a good idea to check whether a query was successful:
if (mysql_query ("insert into jcow_accounts(Time_Spent) values ('{$Time}') where uid='{$client['id']}' ") === FALSE) {
echo 'MySQL error: ' . mysql_error() . "\n";
}
You need to use an UPDATE instead of an insert.
$dtime = getChangeInTime(); // this is the change in time from the last update
mysql_query( "UPDATE jcow_accounts SET `TIME_SPENT` = `TIME_SPENT` + $dtime ".
" where id='{$client['id']}'" );
Try
insert INTO `jcow_accounts` (`Time_Spent`) VALUES ('{$Time}') where uid='{$client['id']}' WHERE `uid` = '{$client['id']}'
Are you sure the uid is in the DB? try running it without the WHERE...

Categories