when update data where id=$row[id] - php

I want to update data row
But the problem is that it is updated All rows
this is my code:
$query = mysql_query("SELECT *
FROM emp
JOIN inv ON emp.name=inv.empname
WHERE inv.empname='".$name."'")
or die ("mysql error query");
$id = $_POST['id'];
$updatestartdate = date('d/m/Y');
$updateenddate = date('d/m/Y');
$status = $_POST['status'];
while ($rowshow = mysql_fetch_assoc($query)){
$timetoshow = unix_time($rowshow['timex']);
//UPDATE
if (isset($_POST['Update']) and $_POST['Update'] == 'dataupdate'){
$updatestatus = mysql_query ("UPDATE inv SET
updatestartdate='$updatestartdate',
updateenddate='$updateenddate',
status='$status'
WHERE id='".$rowshow['id']."'")
or die ("updatestatus Error");
if (isset ($updatestatus)){
echo "<div class='hidecontent'><h3 style='background-color:#3F3F3F; padding:5px;' align='center'>
<font color='#FFFFFF'>Update is done</font></h3><meta http-equiv='Refresh' content='5; url=cpanel_user.php' /></div>";
} else {
echo "<div class='hidecontent'><h3 style='background-color:#FF0000; padding:5px;' align='center'>
<font color='#FFFF00'>Update Error</font></h3></div>";
}
}
Where is problem?

If it's updating all the rows then it probably means that you are not filtering the data which is to be updated. To filter the data, use the WHERE clause. Next ensure that all rows don't have a duplicate values else it would update all the rows as well. Consider the following code:
UPDATE `database` . `table` SET `Name` = 'Zahid Saeed' WHERE `Name` = 'Zahid';
The point is, the person named 'Zahid' is not alone in this world. You have to be more specific. If you can, always use the ID column to update a value as it is always unique just like so:
UPDATE `database` . `table` SET `Name` = 'Zahid Saeed' WHERE `id` = 'Some ID'
If you can't get the ID, use the AND clause to match multiple columns to filter the data more accurately like this:
UPDATE `database` . `table` SET `Name` = 'Zahid Saeed' WHERE `Name` = 'Zahid' AND `Age` = 19 AND `Email` = 'abc#hotmail.com'

Your query should be
"UPDATE inv
SET updatestartdate='$updatestartdate',
updateenddate='$updateenddate',
status='$status'
WHERE id = '".$id."'";

Related

Duplicate entry '1' for key 'PRIMARY' when updating the table

I have a problem when trying to update table after checking row. Not sure if the "if" statement is wrong, however I'm not quite sure, why the UPDATE sql is returning this error. I wouldn't be suprised if INSERT did that.
Here's part of code:
$sql = "SELECT user_id FROM players WHERE user_id = '$id'";
$result = $connect->query($sql);
if($result->num_rows > 0)
{
$sql = "UPDATE players SET user_id = '$Player->user_id', display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
if($connect->query($sql) === TRUE)
{
echo 'Table has been successfully updated.';
}else{
echo 'There has been a problem with updating the "players" table. <br>Error: '.$connect->error;
}
}else{
$sql = "INSERT INTO players(user_id, display_name, attackPower, defensePower) VALUES('$Player->user_id', '$Player->display_name', '$Player->attackPower', '$Player->defensePower')";
if($connect->query($sql) === TRUE)
{
echo'Table has been successfully migrated.';
}else{
echo'Table migration has failed.';
}
}
$connect->close();
INSERTing is working just fine. I would appreciate any advice. Thanks.
Your update query should look like:
$sql = "UPDATE `players` SET `display_name` = '{$Player->display_name}',
`attackPower` = '{$Player->attackPower}', `defensePower` = '{$Player->defensePower'}
WHERE `user_id` = '{$Player->user_id}'";
It cause an error because Identity columns are not updateable.
You can update every columns except them:
$sql = "UPDATE players SET display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
As #aynber and #Julqas said, problem was my sql was missing WHERE condition. Thanks for help.

SQL query doesn't get values

The SQL query returns just Array in the browser even if there is values in the database. I have tried the query in phpmyadmin and it works but not in my php document.
require_once('connect.php');
$query = "SELECT `id` FROM `questions` WHERE round='1' AND year='2016'";
$sql = mysqli_query($dbconnect, $query);
$row = mysqli_fetch_array($sql, MYSQLI_ASSOC);
Almost the same query works in different php documents. Any suggestions what is wrong? Should also say that the query should return integers.
$query = "SELECT `id` FROM `questions` WHERE round='1' AND year='2016'";
You're only selecting the id column. If you wish to echo more columns, then you need to add them in the query.
I.e.:
$query = "SELECT `id`, `col2`, `col3` FROM `questions` WHERE round=1 AND year=2016";
then loop over results:
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)) {
echo $row['id'];
// echo "<br>";
// echo $row['col2'] . "<br>";
// echo $row['col3'];
}
Check for errors on the query also and assuming a successful mysqli_ connection.
http://php.net/manual/en/mysqli.error.php
Other reference:
http://php.net/manual/en/function.mysqli-connect.php
if you want to display other column's data so have to add * in the place of 'id'
require_once('connect.php');
$query = "SELECT * FROM `questions` WHERE round='1' AND year='2016'";
$sql = mysqli_query($dbconnect, $query);

mySql query does not find the row

I'm new to both PHP & mySQL, but I suspect some apostrophe related bug here (maybe).
For some reason the first query always seems to return null because the
echo "result: $result\n";
never prints any data. At the first call that is expected, but at the second call the player has been added to the db. My database works in the sense that I can see that rows with correct ids are added to the database (via phpMyAdmin).
Can you help me spot the error?
<?php
require_once('Db.php');
$db = new Db();
// Quote and escape form submitted values
$id = $db->quote($_POST['id']);
$score = $db->quote($_POST['score']);
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = `$id`");
echo "result: $result\n"; // Never prints any data
if($result->num_rows == 0) {
// Row not found. Create it!
$result = $db->query("INSERT INTO `xxxxxx`.`Player` (`id`,`score`) VALUES (" . $id . "," . 0 . ")");
}
?>
First, drop those backticks from id in WHERE clause, otherwise it will take the field name from id column instead of 'id'.
Then you need to fetch data from $result:
$result = $db->query("SELECT id FROM `xxxxxx`.`Player` WHERE id = '$id'");
$row = $result->fetch_array();
echo $row['id'];
Or if there are more rows than one:
while($row = $result->fetch_array())
{
echo $row['id'];
}
You are using backticks in your query for $id. Remove them and try again.
Your query should be
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = $id");
OR
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = ".$id."");

Query does not work when i fetch data and insert it into a table

I am trying to insert to another table the results of a select statement from another table. The select statement works but the insert statement does not work. Please help me.
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
}
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
header("Location:homeclient.php");
?>
You asked for how to do these two as one query.
This is how:
$query = mysql_query("INSERT INTO `client` ( `client_csub_code`, `client_csub_name`, `client_csub_day`, `client_csub_time` ) SELECT `sub_code`, `sub_name`, `sub_day`, `sub_time` FROM `subject` WHERE `code` = '$enrol'");
// I would also add error checking
if ( mysql_errno() )
echo mysql_error();
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
}
header("Location:homeclient.php");
?>
Try changing to this. Currently your query is outside of your while, it will only run once and the values of $csubject etc are always going to be the last values of your fetched results.

alert mysql column`s comment using php

I want to change my field comment using php but there is a problem!!
I need to get other column`s features :|
this is my code(gets all column features):
$query = "
SELECT
*
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = '$dbName' AND
TABLE_NAME = '$tableName' AND
COLUMN_NAME = '".$row->name."'";
$result = mysql_query($query) or die($query.'<br>'.mysql_error());
$tempRow = mysql_fetch_object($result);
this is my code that changes the comment
$query = "ALTER TABLE `$tableName`
MODIFY `".$row->name."`
".$tempRow->COLUMN_TYPE."
DEFAULT ".$tempRow->COLUMN_DEFAULT."
COMMENT '$comment'" ;
$result = mysql_query($query) or die($query.'<br>'.mysql_error());
but problem is that i lose some features , for example , outo increament , primary key ...
is there any way that i dont need to write all features , just change comment like update query ?!! if not how I should correct this query?!
Sorry about that, but there is no way to just change a single feature. You always have to specify all features that the column has. So extend your query to reflect all the column's features. All you need for that should be in $tempRow.
if ($tempRow->IS_NULLABLE == "NO")
{
$nullStr =" Not null ";
}else
{
$nullStr =" null ";
}
if (strlen($tempRow->COLUMN_DEFAULT) >0 )
{
$defaultStr = "DEFAULT ".$tempRow->COLUMN_DEFAULT;
}else
{
$defaultStr =" ";
}
if (strlen($tempRow->COLLATION_NAME )>0)
{
$collateStr = "collate " . $tempRow->COLLATION_NAME ;
}
$comment .= implode("|",$info);
$query = "ALTER TABLE `$tableName`
MODIFY `".$row->name."`
".$tempRow->COLUMN_TYPE."
".$nullStr."
".$extraStr."
".$defaultStr."
". $tempRow->EXTRA."
". $collateStr."
COMMENT '$comment'" ;

Categories