My code is as follows:
<?php
include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$id=$_POST['id'];
$id = mysql_escape_String($id);
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);
if($count==0)
{
$sql = "update Messages set up=up+1 where mes_id='$id'";
mysql_query($sql);
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$id','$ip')";
mysql_query($sql_in) or die(mysql_error());
echo "<script>alert('Thanks for the vote');</script>";
}
else
{
echo "<script>alert('You have already voted');</script>";
}
$result=mysql_query("select up from Messages where mes_id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['up'];
echo "<img src='button.png' width='110' height='90'>";
echo $up_value;
}
?>
My problem is that the insert process does not take place at all. The script tags echos an alert box. Even the img tag is echoed to the web page. But the insert process does not take place. The config file is fine.
Note: This code works on my local machine which has PHP 5.3 but it does not work on the server which has PHP 5.2.
The only explanation is that the $count==0 check is false. Try with this workaround:
$ip_sql=mysql_query("select count(*) from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$rc=mysql_fetch_row($ip_sql);
$count=$rc[0];
instead of:
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);
Have you tried messing around with the quotes? Someone please correct me if I'm wrong, but AFAIK, variables within single quotes don't get expanded in PHP.
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='".$id."' and ip_add='".$ip."'");
Looking at the answers and comments, it's time to get old school:
$sql = "update Messages set up=up+1 where mes_id='$id'";
echo $sql . '<br>';
mysql_query($sql);
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$id','$ip')";
echo $sql_in . '<br>';
mysql_query($sql_in) or die(mysql_error());
echo "<script>alert('Thanks for the vote');</script>";
What are you looking for?
You are putting values in for $id and $ip - maybe one of them is empty or contains a character that is making the result "odd" in some way. By taking a good look at the raw query that you are about to execute, you'll see if the variable parts of it are upsetting things.
You're not checking if the first query succeeds:
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);
There's no ... or die(mysql_error()) there, but this is most likely not the problem, because if the query was failing, you'd get an "invalid statement handle" type error when you do the mysql_num_rows() call immediately afterwards. As a stylistic tip, I'd suggest rewriting the first query as follows:
SELECT COUNT(*) FROM Voting_IP
WHERE (mes_id_fk = $id) AND (ip_add = $ip)
You're not using any of the retrieved values, just the row count, so there's no point in doing a "select *" type query, which forces the database to do at least SOME processing on all the possible values. If this system scales to very large numbers of votes and IPs, using the count() version will be more efficient.
You say the insert doesn't take place, but don't say which alert() occurs, which means either there's an error with the insert query, or your first query returns 0, and the whole block with the insert query is skipped.
Have you tried manually running the update/insert queries? You're not checking if the update succeeds, as there's no or die(mysql_error()) afterwards. Perhaps there's a foreign key error, a syntax error, etc...
If you're updating an entry based on an ID, then obviously you want to update and insert when the count is NOT zero.... or greater than zero,.. or 1
Simply taking out the == 0, should fix it
if($count)
{
$sql = "update Messages set up=up+1 where mes_id='$id'";
mysql_query($sql);
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$id','$ip')";
mysql_query($sql_in) or die(mysql_error());
echo "<script>alert('Thanks for the vote');</script>";
}
Related
I've tried to follow several answers on this question but can't seem to get it to work for my specific problem.
I want to insert data but only if the flight_number doesn't exists already. How can I do that?
$sql = mysqli_query($con,
"INSERT INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Rob since you saying flight_number is a unique then you can use INSERT IGNORE
<?php
$sql = "INSERT IGNORE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`) VALUES (?,?,?,?)";
$stmt = $con->prepare($sql);
$stmt->bind_param('isss',$flight_number,$mission_name,$core_serial,$payload_id);
if($stmt->execute()){
echo 'data inserted';
// INSERT YOUR DATA
}else{
echo $con->error;
}
?>
OR you could select any row from your database that equal to the provided flight number then if u getting results don't insert.
$sql = "SELECT mission_name WHERE flight_number = ? ";
$stmt = $con->prepare($sql);
$stmt->bind_param('i',$flight_number);
if(mysqli_num_rows($stmt) === 0){
// INSERT YOUR DATA
}
A unique index on flight number should do the trick.
CREATE UNIQUE INDEX flight_number_index
ON space (flight_number);
If you want to replace the existing row with the new one use the following:
$sql = mysqli_query($con,
"REPLACE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Make note that I just copied your code and changed INSERT to REPLACE to make it easy to understand. PLEASE PLEASE PLEASE do not use this code in production because it is vulnerable to injection.
If you don't want to replace the existing row, run an insert and check for errors. If there is an error related to the index, the row already exists.
Disclaimer: I haven't tested any of this code, so there may be typos.
I'm working on a script, but it won't work.
When a user makes a post, NOW() will be inserted. I want to make a script where the user will only be able to make a post when his last post differs at least 10 minutes from the post he wants to make at this moment. I don't want to make use of cookies, seeing people can delete them.
I have this code at the moment, but don't know how to move on. Thank you!
if ($db_found) {
$sql1="SELECT send_time FROM bloopp WHERE email='$email' ORDER BY id DESC LIMIT 1";
while($row = mysqli_fetch_array($result)) {
$last_post = $row['send_time'];
}
if ($last_post + 600 >= NOW() {
sql2 = "INSERT INTO bloopp (bloopp, browser, medium, send_time, email) VALUES
('$bloopp', '$browser', 'desktop', NOW(), '$email')";
$result = mysql_query($sql);
if($result) {
header('Location: index.php');
}
else {
echo "ERROR";
}
}
}
When dealing with time, it's handy if you can rely entirely on the database. This avoids mixing up the database conception of time with PHP's, which may be on different servers and/or have different time configuations.
So, try to locate a post made in the last ten minutes, and if there isn't one, you know you are good to go
SELECT COUNT(*) AS recent_posts
FROM bloopp
WHERE email=? AND (UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(send_time))<600;
on the query you have :
sql2 = "INSERT INTO bloopp (bloopp, browser, medium, send_time, email) VALUES ('$bloopp', '$browser', 'desktop', NOW(), '$email')";
$result = mysql_query($sql);
shouldn;t that be
$sql = "INSERT INTO bloopp (bloopp, browser, medium, send_time, email) VALUES ('$bloopp', '$browser', 'desktop', NOW(), '$email')";
mind the sql2 / $sql replacement
Lets say you have table user
user_table:
id
email
bloop:
email
browser
....
Select * from user_table left join ( select max(send_time),email from bloop where email=$email ) max_sel on max_sel.email = user_table.email...
Something like this will get the user with his latest post (or null for new users who do not have a post, check put left joins), put the date in session and when he posts update it and such, you know how to do this.
Regards
How would I go about validating this query? Currently, I getting some omissions where one row hasn't copied over so I need a bombproof method to check and correct. Query:
$query = "
SELECT *
FROM $UID
";
$result = mysql_query($query)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$q = $row['QID'];
$a = $row['answer'];
$c = $row['comment'];
$query = "
INSERT INTO a (UID, QID, answer, comment)
VALUES ('$UID', '$q', '$a', '$c')
";
mysql_query ($query)or die(mysql_error());
}
Thanks.
You can do this in a single query.
INSERT INTO a (UID, QID, answer, comment)
SELECT '$UID', QID, answer, comment FROM `$UID`
As its an atomic operation all the data will be copied in one shot. However you can still verify by using mysql_info function. It'll give output like following.
Records: 23 Duplicates: 0 Warnings: 0
Here Duplicate is the number of rows there were discarded due to duplicate key. If both Duplicates and Warning are 0 you can say query was successful.
I am trying to perform a update/insert into query for MySQL. Should insert, if not already in database.
However, it will not update. My db connection is good. I cannot figure it out.
$sql = "UPDATE jos_bl_paid SET u_id='$uid', m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND '$mid' = m_id ";
$test45 = mysql_affected_rows();
if ($test45 == 0) {
$sql = "INSERT INTO jos_bl_paid(paypal_payment,u_id,m_id,pd,t_id,p_date)VALUES('$txn','$uid','$mid','1','$cus',NOW())";
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
echo 'Yes';
}else{
echo 'No';
}
From the code you are showing you aren't even running the update query. You need to put
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
before the line
$test45 = mysql_affected_rows();
for that to even return what you want
I would make these into one statement using the ON DUPLICATE KEY UPDATE mysql command. I would guess that your problem is that the insert may be failing because of some unique key set in you schema even though the actual uid doesn't yet exist so the update also fails. Can you post exactly what error message you get?
check your last value in update query i found an error there and have fixed it from my side
try this
$sql = mysql_query("UPDATE jos_bl_paid SET u_id='$uid',m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND m_id = '$mid'") or die(mysql_error());
Answer is updated try the updated one
From the code you posted, it appears that you're setting the $sql string to an update statement, but not executing it before checking for the number of affected rows.
You'll probably need to call mysql_query($sql) before checking mysql_affected_rows();
Otherwise you're not telling the database to update anything.
If the new values in update are the same as old one mysql won't update the row and you will have mysql_affected_rows be 0. If you have primary key on fields u_id, m_id you can use INSERT ON DUPLICATE UPDATE http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If you don't have such you may use the count query:
SELECT count(*) FROM jos_bl_paid WHERE u_id = '$uid' AND '$mid' = m_id
To decide if you should update or insert new one.
i have tried to prevent the duplicate data at my project.
but until now it still make duplicate.
i try this code but still not work:
$cek_user= "SELECT Model, Serial_number, Line FROM inspection_report WHERE Model='".$Model."' AND Serial_number='".$Serial_number."' AND Line='".$Line."'";
$cek_data=mysql_num_rows($cek_user);
if($cek_data!=0){
echo "Data already exists!";
}
else{
$sql = "INSERT INTO inspection_report ";
$sql.= "(Model, Serial_number, Line, Shift, Inspection_datetime, Range_sampling, Packing, ";
$sql.= "Accesories, Appearance, Tuner, General_operation, Remark, ";
$sql.= "NIK) ";
$sql.= "VALUES ('";
$sql.= $Model."','".$Serial_number."', '".$Line."','".$Shift."','".postVar('insp_date')." ".postVar('time')."','".$Range_sampling."','".$Packing."','";
$sql.= $Accesories."','".$Appearance."','".$Tuner."','".$General_operation."','".$Remark."','";
$sql.= $NIK."')";
//echo $sql;
$result=mysql_query($sql) or die(_ERROR26.": ".mysql_error());
//echo $result;
}
mysql_close($dbc);
}
but still not work,please help.
This will not prevent duplicates unless your table also has a UNIQUE constraint somewhere allowing the database to determine what you mean by a duplicate. If you have such a constraint, perhaps you could post your table definition.
You can do a select before insert,
eg. Select id from table where serial_number = '$serial_number'
If mysql_num_rows equals 0, do insert. This assumes serial_number is unique for each row.
$sql = "SELECT ID FROM inspection_report WHERE Serial_number = '$Serial_number'";
$result = mysql_query($sql);
if(mysql_num_rows($result) == 0){
$sql = "your insert sql..."
$result = mysql_query($sql);
}
You do realize your're running the INSERT query twice, right?
if ( mysql_query($sql) ) {
^^^^^^^^^^^--- here
[.... snip ....]
}
$result=mysql_query($sql) or die(_ERROR26.": ".mysql_error());
^^^^^^^^^^^--- and here
As well, you should look into using HEREDOCs to build your query string. That long chunk of string concatenation and quote-soup you've got could look like this with a HEREDOC:
$insp_date = postVar('insp_date') . ' ' . postVar('time');
$sql = <<<EOL
INSERT INTO inspection_report
(Model, Serial_number, Line, Shift, Inspection_datetime,
Range_sampling, Packing, Accesories, Appearance, Tuner,
General_operation, Remark, NIK)
VALUES (
$Model, $Serial_number, $Line, $Shift, $insp_date,
$Range_sampling, $Packing, $Accesories, $Appearance, $Tuner,
$General_operation, $Remark, $NIK)
EOL;
every so slightly more readable.
edit/comment followup:
You're running the query twice, in the spots where I've put the '^^^^^--- here' lines.
First instance: if ( mysql_query($sql) ) {
Second instance: $result = mysql_query($sql) or die.......
You haven't changed the contents of $sql between the two mysql_query() calls, so when you do the second call, it runs the exact same query string, which is your INSERT query. So you end up inserting the data TWICE.
Beyond that, your error handling is atrocious. Scanning an error string for a particular string is the wrong way to go about it. The error text might change (think of what would happen if your code runs on a server running in (say) a German location, which has localized error messages and spits out "Doppelter eintrag für ..." instead of "Duplicate entry for". What you should have is something like this:
$sql = "... your query here ... "
$result = mysql_query($sql); // if query fails, this returns FALSE
if ($result === FALSE) {
die("MySQL error: " . mysql_error());
}
If you need to check for a particular error that could be corrected by your code, you can use mysql_errno() to retrieve the server error code, and work from there. Using your example, 'Duplicate entry' is error # 1062 (full error codes documented here), so you'd do
if (mysql_error() == 1062) {
... handle error here ...
}
first of all:
ALTER inspection_report ADD UNIQUE(Model, Serial_number, Line);
Then:
$sql = "INSERT IGNORE INTO..........";