Update not working i can't find my error - php

My update script is not working.. I don't know what im missing..
but i can't update the table ... Went to w3school to know about the update in php but still it wont work...
-noob coder-
<?php
include 'Core/init.php';
protect_page();
include 'Includes/Overall/overallheader.php';
?>
<h1>Update School Year and Semester</h1>
<?php
$con=mysqli_connect("localhost","root","1234","database3");
// Check connection
$sy = $_POST['school_year'];
$sem = $_POST['semester'];
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ( isset($_POST['submit'] ) )
{
$sql = "UPDATE `activesys` SET `activeschoolyear` = '$sy' AND `activesemester` = '$sem'";
$exec = mysql_query($sql) or die(mysql_error());
}
?>
<form action="" method="post">
<ul>
<li>
School Year:<br />
<input type="text" name="school_year">
</li>
<li>
Semester:<br />
<input type="text" name="semester">
</li>
<li>
<input type="submit" value="submit">
</li>
</ul>
</form>
<?php
include 'Includes/Overall/overallfooter.php';
?>

Even though its not directly realated:
Please make sure to escape Request data that you load from $_POST or $_GET by using mysql_escape_string . Otherwise it would be easy to inject SQL in your query, which would allow to run harmfull sql in your system, like deleting the database or manipulating the data.
http://en.wikipedia.org/wiki/SQL_injection

You have missed where condition in update query .. try this
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
$sql = "UPDATE `activesys` SET `activeschoolyear` = '$sy' AND `activesemester` = '$sem'" WHERE some_column=some_value;

First, you mix mysqli and mysql. Second, mysql_query/mysqli_query have two parameters. Third, your sql is not right.
So, change your $exec = mysql_query($sql) or die(mysql_error())
to $exec = mysqli_query($con,$sql) or die(mysqli_error($con));
change your sql to :
$sql = "UPDATE `activesys` SET `activeschoolyear` = '$sy' , `activesemester` = '$sem'";
but you didn't have a where condition here, if in your table you have set an
anto-increment key and set it to primary key, you could add some condition end of you sql,otherwise it will
update all your records.
$sql = "UPDATE `activesys` SET `activeschoolyear` = '$sy' , `activesemester` = '$sem' where id={$id}"
$id is one recod from you table.
this should work for you excute an update..

Try using this :
1) use "action" attribute of the tag
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
2) check whether your form has beensubmitted :
if(isset($_POST['submit']))
3) Use WHERE condition in your sql query. You final query should look like this :
<?php
if(isset($_POST['submit']))
{
$con = mysqli_connect("localhost","root","1234","database3");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$query = "
UPDATE `activesys`
SET `activeschoolyear` = '$sy',`activesemester` = '$sem'
WHERE `columnName` = `columnValue`
";
mysqli_query($con,$query);
}

Related

Trying to get a mysql table id row into php variable to base futher mysql queries from it

I am programming in a PHP, HTML and SQL and got stuck in some part of my project.
In the following code I tried to recieve an string that is meant to represent a name of a movie from a textbox after a button press. I then tried to search for ID of that film and then in everyother table where that ID is present I tried to remove all data tied to that ID then remove the data about the movie from the main table itself. Yet I run in tons of different errors I can't handle whenever I try another approach.
Could someone point me a nice way to remove all table records about a movie with ID for example 3 when the movie name is The Green Mile?
<?php
IF ($_SERVER["REQUEST_METHOD"] == "POST") {
$con=mysqli_connect("localhost","root","","bazus");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysql_query('SET foreign_key_checks = 0');
$tytul = mysqli_real_escape_string($con, $_POST['tytul']);
$id = "SELECT id FROM filmy WHERE tytul=$tytul";
$dana = mysql_query($id);
$film_przyznano = "DELETE FROM przyznana WHERE filmy_id='$dana'";
$premiera = "DELETE FROM premiera WHERE filmy_id='$dana'";
$obsada = "DELETE FROM obsada WHERE filmy_id='$dana'";
$film_gatunek = "DELETE FROM film_gatunek WHERE filmy_id='$dana'";
$rezyseria = "DELETE FROM rezyseria WHERE filmy_id='$dana'";
$scenariusz = "DELETE FROM scenariusz WHERE filmy_id='$dana'";
$film_producent = "DELETE FROM film_producent WHERE filmy_id='$dana'";
//mysql_query($film_przyznano);
//mysql_query($obsada);
//mysql_query($premiera);
//mysql_query($film_gatunek);
//mysql_query($rezyseria);
//mysql_query($scenariusz);
//mysql_query($film_producent);
/*$sql="DELETE FROM filmy WHERE tytul='$tytul'";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record deleted";
$tytul="";*/
mysql_query('SET foreign_key_checks = 1');
}
?>
<div id="remove">
<form action='<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>' method='post'>
<input type="text" name="tytul">
<input type="submit">
</form>
</div>
It seems to me that you code is good. What you are lacking is error handling. If line 13 does not return a result, then $dana is equal to nothing, which will toss an error for all the result of your queries.
You should add a line after that something like this
if ($dana > 0) {
// do your delete queries
} else {
// do nothing echo error
echo "No movie found";
}

PHP/HTML Form not updating MySQL

I can't seem to find a solution to this and i've looked for similar threads too but no luck
Basically here's my code, when you click Update it's meant to display your current name in the form fields then you can overwrite them and submit the changes, however sadly it will not update, it only displays the originally set first name and last name and does not update the database so therefore not displaying the new set names.
<?php
include('../connect_db.php');
$res = mysqli_query($dbconnection, "SELECT * FROM users");
$row = mysqli_fetch_array($res);
if(isset($_POST['newFirst']) && isset($_POST['newLast'])){
$newFirst = $_POST['newFirst'];
$newLast = $_POST['newLast'];
$id = $_POST['id'];
$sql = "UPDATE users SET first_name='$newFirst', last_name='$newLast' WHERE id='$id'";
$res = mysqli_query($dbconnection, $sql);
}
?>
<div id="editSection">
<h3>Edit Details</h3>
<form action="edit_profile.php" method="POST">
<input type="hidden" value="<?php echo $row[0];?>" name="id"/>
<h2>First Name</h2>
<input type="text" name="newFirst" value="<?php echo $row[1];?>">
<h2>Last Name</h2>
<input type="text" name="newLast" value="<?php echo $row[2];?>">
<input type="submit" value="Update">
</form>
</div>
Any help would be greatly appreciated :)
Kind Regards
~ Matt
You have to connect to DB before updating.so use
$con=mysqli_connect("localhost","my_user","my_password","my_db");
There are several other errors like you have to make $POST['newFirst'] as $_POST['newFirst'] like this
if(isset($_POST['newFirst']) && isset($_POST['newLast'])){
And change the query to
$sql = "UPDATE users SET first_name='$newFirst',last_name='$newLast' WHERE id= '$id'";
beacuse you have error at end of query id='first_name='$id' which is wrong
I see some error in the query
$sql = "UPDATE users SET first_name='$newFirst',
last_name='$newLast' WHERE id='first_name='$id'";
should be
$sql = "UPDATE users SET first_name='$newFirst',
last_name='$newLast' WHERE id= '$id'";
also
if(isset($POST['newFirst']) && isset($POST['newLast'])){
should be
if(isset($_POST['newFirst']) && isset($_POST['newLast'])){
You are using $POST wrong in your if-condition.
It must be called $_POST[..].
Also you should take a look at your WHERE in your update query.
I think you mean: WHERE id= '$id'
You should get your id from $_POST['id']; which is your row ID i suppose and also the update query must be where id=$id.
$id = $_POST['id'];
$sql = "UPDATE users SET first_name='$newFirst', last_name='$newLast' WHERE id=$id";
Also have you checked in DB after the update? the row[0], row[1], row[2] used will have old set of values used during select before the update happened. can you have the mysqli_fetch_array($res) after the update call?

Display a specific value from database in a html

Im pretty new on making webpages. But i´m doing a homepage with forms to Insert to my database. Thats no problem, my problem is that I want to show a specific column from the last row. And the code that I've got so far is this:
<html>
<body>
<form action="insert.php" method="post">
Publiceringsdag (OBS! En dag tidigare an foregaende):<br>
<?php
$con=mysqli_connect("localhost","rss","Habb0","kalender");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$lastPub = mysql_query("SELECT DISTINCT pub FROM event ORDER BY `id` DESC LIMIT 1")
or die(mysql_error());
echo $lastPub
?>
<br>
<input type="text" name="pub"><br>
<input type="submit">
</form>
</body>
</html>
Actually, it is not a very good idea to use the deprecated mysql_ functions. Look at PDO or Mysqli instead.
Meanwhile, in your current implementation you just need to fetch your data after the query execution:
$con = mysql_connect("localhost", "rss", "Habb0", "kalender");
if (mysql_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
$lastPub = mysql_query("SELECT DISTINCT pub FROM event ORDER BY `id` DESC LIMIT 1")
or die(mysql_error());
if($row = mysql_fetch_assoc($lastPub)))
$result = $lastPub['pub'];
Now the result should be in your $result variable.
EDIT: I just noticed that in your code you use mysqli_connect, mysqli_connect_errno and mysql_query, mysql_error at the same time. But they belongs to different PHP extensions.
You must fetch the result first:
$lastPub = mysql_query("SELECT DISTINCT pub FROM event ORDER BY `id` DESC LIMIT 1")
or die(mysql_error());
$result = mysql_fetch_array($lastPub);
echo $result['pub'];
Try this.
<html>
<body>
<form action="insert.php" method="post">
Publiceringsdag (OBS! En dag tidigare an foregaende):<br>
<?php
$con=mysql_connect("localhost","rss","Habb0") or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db("kalender",$con) or die("Failed to connect to MySQL: " . mysql_error());
$result = mysql_query("SELECT DISTINCT pub FROM event ORDER BY `id` DESC LIMIT 1");
$data = mysql_fetch_array($result);
echo $data['pub'];
?>
<br>
<input type="text" name="pub"><br>
<input type="submit">
</form>
</body>
</html>

Can't check which check list is checked

I'm trying to delete multiple pictures using checkbox item. But somehow pictures are not deleted from database.
the coderuns without mistake. Page is being redirected but the delete query is not executed.
I believe there is somethong to do with passing picture id to query $List[1] but i really can't understand what.It seems I'm doing everything ok.
Thanks for any help in advance.
That's the code:
<?php
$Connection = mysql_connect( $Host, $User, $Pass ) or die('ERROR: '.mysql_error());
mysql_select_db( $DataBase )or die('ERROR: '.mysql_error());
$Query = "SELECT * FROM pictures WHERE folder_id = ".$FolId.";";
$Picture = mysql_query($Query, $Connection)or die('ERROR: '.mysql_error());
?>
<form name='Photos' method='POST' >
<?php
while($List = mysql_fetch_array($Picture)){
echo "<input type='checkbox' name='photoList[]' value='".$List[1]."'> <span> ".$List[4]."</span>";
}
?>
<input type='submit' name='Delit' value='DELETE' >
</form>
<?php
if(isset($_POST['Delit'])){
foreach($_POST['photoList'] as $item){
$Query="DELETE FROM pictures WHERE picture_id =".$item;
mysql_query($Query, $Connection)or die("ERROR: ".mysql_error());
header('Location: photos.php');
}
}
?>
My guess is that $List[1] doesn't contain your picture_id. It's probably $List[0].
Using fetch_array is not a great way to get data from a DB using SELECT *, as your columns may change position, and an index doesn't clearly say which column you're retrieving.
Try using fetch_assoc instead, to get the column names associated with the data.
<?php
// Change `picture_name` below to the name of the column storing your picture's name
while ($List = mysql_fetch_assoc($Picture)) {
echo "<input type='checkbox' name='photoList[]' value='{$List['picture_id']}'> <span> {$List['picture_name']}</span>";
}
?>
Also, try this for your DELETE logic:
Checking if photoList is set (vs. Delit)
Looping through your photo list and casting the values to (int) to prevent SQL Injection
Concatenating the list of IDs into a comma-delimited list using implode
Doing a DELETE... WHERE IN query, providing the photo ID list - this is much faster than looping through and doing several DELETE... WHERE = statements
Code:
<?php
if (isset($_POST['photoList']) && !empty($_POST['photoList'])) {
$photoIds = array();
foreach ($_POST['photoList'] as $photoId) {
$photoIds[] = (int) $photoId;
}
$photoIds = implode(',', $photoIds);
$Query = "DELETE FROM pictures WHERE picture_id IN ({$photoIds})";
mysql_query($Query, $Connection)or die("ERROR: ".mysql_error());
header('Location: photos.php');
}
?>

MySQL update doesn't work

I want to update 2 of my database's fields according to user input.My code is something like this:
<body>
<?php
$db_server["host"] = "localhost"; //database server
$db_server["username"] = "root"; // DB username
$db_server["password"] = "mypass"; // DB password
$db_server["database"] = "mudb";// database name
$dbc = mysql_connect($db_server["host"], $db_server["username"], $db_server["password"]);
mysql_select_db($db_server["database"], $dbc);
$user = $_COOKIE['mycookie'];
$q = "SELECT * FROM members WHERE username='$user'";
$r = mysql_query( $q,$dbc);
while ($row = mysql_fetch_array($r, MYSQLI_ASSOC)) {
echo 'username: '.$row['username'], '<br/>';
$password=$row['password'];
?>
<form method="post" id="changepasswordform" >
<input type="password" id="newpassword" name="newpassword"/>
<input type="submit" name="changepasswordbutton" >
</form>
<?php
echo 'email: '.$row['email'], '<br/>';
}
?>
<form method="post" id="changeemailform" >
<input type="text" id="newemail" name="newemail"/>
<input type="submit" value="αλλαγή" name="changeemailbutton" >
</form>
<?php
}
if (isset($_POST['changepasswordbutton'])){
$newpassword=$_POST['newpassword'];
$q2 = "UPDATE members SET password=$newpassword WHERE username='$user'";
$r2 = mysql_query($q2,$dbc);
}
if (isset($_POST['changeemailbutton'])){
$newemail=$_POST['newemail'];
$q3 = "UPDATE members SET email=$newemail WHERE username='$user'";
$r3 = #mysql_query( $q3,$dbc);
}
?>
</body>
However although my connection to my db is ok(SELECT displays results as expected) when i try to UPDATE , the values inside my db remain the same.I checked the values of $newpassword and $newemail and they do contain the user inputs each time.What am i missing here?
You're missing the '' (quotes) that supposed to surround the password field.
change:
UPDATE members SET password=$newpassword WHERE username='$user'
to:
UPDATE members SET password='{mysql_real_escape_string($password)}'
WHERE username='{mysql_real_escape_string($user)}'
IMPORTANT:
And even though it's not related, please don't use mysql_* functions - it's deprecated and vulnerable to sql-injection. Better use PDO or MySQLi.
This will do the trick and is save for sql injection (mysql_real_escape_string):
$q2 = "UPDATE members SET
password='". mysql_real_escape_string($password) ."'
WHERE username='". mysql_real_escape_string($user) ."';
But off course you shouldn't use mysql_* anymore, I'm just giving an example for your specific case.

Categories