Updating PHP4 to PDO - php

I'm currently managing a little database for a club and I'm starting to feel more and more pressure to update the thing to PHP5. The only thing is that I'm not quite a 100% sure on how to convert this structure without messing up the whole thing. (Or starting from scratch)
Could you guys tell me if this is easily editable/updatable or if I should redo everything? (The total file is 800 lines, so I hope to not have to redo it :P)
So I open the databse with:
//Database connection settings
$mysql_server = "localhost";
$mysql_user = "user";
$mysql_password = "pass";
$mysql_database = "database";
//Connect using settings
$connection = mysql_connect("$mysql_server","$mysql_user","$mysql_password")
or die ("Unable to connect to MySQL server.");
$db = mysql_select_db("$mysql_database")
or die ("Unable to select requested database.");
Then I can create users with:
if($changeme ==1) //if user pressed save, then update table
{
$name = mysql_real_escape_string($_POST["name"]);
mysql_query("INSERT INTO Members (name,) VALUES
('$name')") or die(mysql_error());
//show end text
echo "Edit complete!<br />
<form><input type='button' onClick=\"parent.location='users.php'\" value='OK'></form>";
}else{//user didn't press save
?>
<!--Edit form-->
<form action="users.php?new=1&changeme=yes" method="post">
Naam:<br>
<input name="name" type="text" value="" size="79"><br>
<input type="submit" name="Submit" value="Create">
<input type='button' onClick="parent.location='users.php'" value='Back to list'>
</form>
}
I left out everything but name to make it shorter, it has like 30 fields.
Next we can also edit the profiles like this:
if($changeme ==1) //if user pressed save, then update table
{
$id = $_POST['id']; //get ID from form
$name = $_POST["name"];
mysql_query("UPDATE Members SET name='$name' WHERE id='$id'") or die(mysql_error());
//show end text
echo "Edit complete!<br />
<form><input type='button' onClick=\"parent.location='users.php'\" value='OK'></form>";
}else{//user didn't press save
$id = $_GET['edit'];
$sql = "SELECT * FROM Members WHERE id='$id'";
$self = mysql_query($sql);
while ($row = mysql_fetch_array($self)) {
$name = $row["name"];
}
?>
<!--Edit form-->
<form action="users.php?edit=<?php echo $id ?>&changeme=yes" method=post>
<input type="hidden" name="id" value="<?php echo $id ?>">
Name:<br>
<input name="name" type="text" value="<?php echo $name ?>" size="79"><br>
<input type="submit" name="Submit" value="Change">
<input type='button' onClick="parent.location='users.php'" value='Back to list'>
</form>
<?php
}//didn't press save

Related

How to fix data duplicating issue when i try to submit a form

I have a serious issue.
When I submit a form a second time, with new data, then all other data goes duplicate with the last submission's data. Also, when I update any one of the columns it goes all the column data duplicate.
Html Form
<form id="myForm" class="form-horizontal" role="form" method="post" action="">
<input class="inputs" type="hidden" required id="id" name="id" placeholder="*Code...">
<input class="inputs" type="number" required id="code" name="code" placeholder="*Code...">
<input class="inputs" type="text" required id="product" name="products" placeholder="*Products...">
<input type="text" autocomplete="off" placeholder="*Suppliers..." name="supplier" id="supplier" class="inputs">
<input class="inputs" type="number" required id="price" name="price" placeholder="*Price...">
<button class="btn btn-primary" onclick="SubmitForm();" value="send"> Save </button>
</form>
Search.php
<?php
header('Content-Type: application/json');
$response = array();
if (isset($_GET['scode'])){
//vul hier je database gebuikersnaam en ww in
$con=mysqli_connect("localhost", "root", "", "waqar");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qry = "SELECT * FROM products WHERE code = '".$_GET['scode']."' ";
$result = mysqli_query($con, $qry); //mysql_query($qry);
while ($row = mysqli_fetch_array($result, MYSQL_BOTH)) {
array_push($response, $row);
}
echo json_encode($response);
}
?>
Submit.php
<?php
// Establishing connection with server by passing "server_name", "user_id", "password".
$connection = mysql_connect("localhost", "root", "");
// Selecting Database by passing "database_name" and above connection variable.
$db = mysql_select_db("waqar", $connection);
$scode = $_POST['code']; // Fetching Values from URL
$sproduct = $_POST['products'];
$sprice = $_POST['price'];
$ssupplier = $_POST['supplier'];
//echo $semail;
$query = mysql_query("update products set products='$sproduct', price='$sprice', supplier='$ssupplier'"); //Insert query
$query = mysql_query("INSERT INTO products (code,products,price,supplier) values('$scode', '$sproduct', '$sprice', '$ssupplier') on duplicate KEY UPDATE
code='$scode', products='$sproduct', price='$sprice', supplier='$ssupplier'");
if($query){
echo "Data Submitted succesfully";
}
mysql_close($connection); // Connection Closed.
?>
I want to know why that data is duplicating after submission. Thanks in advance.
You are both updating and inserting your records. Also, why are you using MySQL and MySqli in two different forms? Do not use MySQL_connect.
$query = mysql_query("update products set products='$sproduct', price='$sprice', supplier='$ssupplier'"); //Insert query
$query = mysql_query("INSERT INTO products (code,products,price,supplier) values('$scode', '$sproduct', '$sprice', '$ssupplier') on duplicate KEY UPDATE
code='$scode', products='$sproduct', price='$sprice', supplier='$ssupplier'");

Cant Update SQL data using this code, checked code so many times

I wrote this code to update entry in my sql table, but i don't what is wrong.
Here is my form
<form action="" method="POST">
<center>
Alumni_ID :
<input type="text" name="valueh">
<br>
<input type="text" name="name" placeholder="name">
<input type="text" name="phone" placeholder="contact details">
<input type="text" name="details" placeholder="details">
<input type="text" name="address" placeholder="address">
<input type="submit" value="update data">
</center>
</form>
And this is php page,
<?php if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tssolutions";
$ab = $_POST['name'];
$bc = $_POST['phone'];
$cd = $_POST['details'];
$de = $_POST['address'];
$posted = $_POST['valueh'];
//create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "connected successfully";
$sql = " UPDATE phone SET name='".$ab."', phone='".$bc."', details='".$cd."', address='".$de."' WHERE name = '".$posted."' ";
if(mysqli_query($conn, $sql)) {
echo "<hr>";
echo "<h3 class='w3-center' style='text-color:black'>Record Successfully Updated</h3>";
} else {
echo "<hr>";
echo "<h3 class='w3-center' style='text-color:black'>Error While Updating, Try Again</h3>";
}
mysqli_close($conn);
} ?>
Both the code are on same page Update.php, i wish to send alumni_id so that i can update that record where alumni_id = name in table phone, and then send new values of the row .
You forgot to name the submit button
Instead of
<input type="submit" value="update data">
Try this
<input type="submit" name="submit" value="update data">
To debug your code you can echo your SQL statement
echo $sql = "UPDATE phone SET name='".$ab."', phone='".$bc."', details='".$cd."', address='".$de."' WHERE name = '".$posted."';
You can then see if you have correct syntax and your values are sent correctly
try this code, maybe this helps
$sql = " UPDATE phone SET `name` ='$ab', `phone` ='$bc', `details` ='$cd', `address`='$de' WHERE `name` = '$posted' ";

Can't get ID to insert into database from HTML Form (using PHP)

Right now I am trying to create a edit form for my forum, and while I CAN get it to edit, it does not insert an ID to the database (rendering it 0 and thus faulty), the ID field have Auto increment and I've double checked it is the primary field. Tried looking over it many times, but there's got to be something I am missing.
The DB connection:
<?php
error_reporting(E_ALL);
session_start();
$host = 'HOSTNAME';
$dbusername = 'USERNAME';
$dbpassword = 'PASSWORD';
$anslutning = mysqli_connect($host, $dbusername, $dbpassword) or die("<b>Could not connect to database server</b>");
$anslutning->select_db('DATABASE NAME') or die("<b>Could not connect to the specified database</b>");
?>
The form where you edit the post ($edit in this scenario is the ID it grabs when clicking "edit" on a post), as well as where I try to update the database field.
<?php
if(isset($_GET['edit'])) {
// If click on "edit"
$edit = $_GET['edit'];
// The post-editing ID
$getEditData = $anslutning->prepare("SELECT postId, title, content FROM tblPosts WHERE postid='$edit' LIMIT 1");
$getEditData->bind_result($postId, $title, $content);
$getEditData->store_result();
$getEditData->execute();
while($row = $getEditData->fetch()) {
echo '
<div class="editForm">
<form action="index.php" method="POST">
<input type="hidden" name="author" value="'.$_SESSION['loggedIn'].'">
<input type="hidden" name="edit" value="'.$edit.'">
Title: <input type="text" name="new_title" value="'.$title.'"> <br /> <br />
Content: <textarea name="new_content"> '.$content.' </textarea> <br /> <br />
<input type="submit" name="editPost">
</form>
</div>
';
}
}
// Issue(s): Editing a post does not send postId/edit(id) to database
if(isset($_POST['editPost'])) {
$edit = $_GET['edit'];
$author = $_POST['author'];
$new_title = $_POST['new_title'];
$new_content = $_POST['new_content'];
$updatePost = $anslutning->prepare("UPDATE tblPosts SET postId=?, author=?, title=?, content=?");
$updatePost->bind_param("isss", $edit, $author, $new_title, $new_content);
$updatePost->execute();
echo 'Post updated. Redirecting..';
sleep(1);
echo '<script> window.location.href = "index.php?forum=1" </script>';
}
?>
Change
$edit = $_GET['edit'];
to
$edit = $_POST['edit'];

PHP page inserts a blank record as soon as user visits page. Why?

I have this basic php insert script working fine and it will insert the form perfectly once the user hits submit. However, for some reason it also submits a record when the user simply visits the page before they even hit submit. Right away at the top it echoes "Entry Successful" before the user even does anything. There will be a blank record in the database. Why is this happening?
As a bonus question...can I prevent sql injection buy simply adding some mysql_escape code to various parts of this? It is a WordPress page, so is that even necessary?
<?php
$user_ID = get_current_user_id();
$hostname = "******";
$username = "******";
$dbname = "******";
$password = "*****";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
// Get values from form
$genre = $_POST['genre'];
$movie_name = $_POST['movie_name'];
$movie_text = $_POST['movie_text'];
$query = "INSERT INTO movies (ID, genre, movie_name, movie_text) VALUES
('$user_ID','$genre','$story_name','$story_text')";
$result = mysql_query($query);
if($result)
{
echo("
Entry Succesful");
}
else
{
echo("
failed to start");
}
?>
Get started!
<br><br>
<form name="movie" action="" method="post">
What type of movie? <select name="genre">
<option value="">Select...</option>
<option value="Comedy">Comedy</option>
<option value="Drama">Drama</option>
</select>
Name of Movie: <input type="text" size="55" name="movie_name">
<textarea rows="30" cols="80" name="movie_text" rows="4"></textarea>
<input type="submit" name="submit" id="submit" value="Add movie" />
</form>
"However, for some reason it also submits a record when the user simply visits the page before they even hit submit."
Wrap your code inside an (if) isset() conditional statement, using your (named) submit button as a reference:
<?php
if(isset($_POST['submit'])){
$user_ID = get_current_user_id();
...
else
{
echo("
failed to start");
}
} // end brace for if(isset($_POST['submit']))
?>
Get started!
<br><br>
<form name="movie" action="" method="post">
<input type="submit" name="submit" id="submit" value="Add movie" />
...
</form>
As far as SQL injection goes, visit:
How can I prevent SQL-injection in PHP?
on Stack.
You need to check whether user is hitting submit button or not, else php script will execute every time you run a page or request a page. you can use isset to check that. try below code
<?php
if(isset($_REQUEST['submit']))
{
$user_ID = get_current_user_id();
$hostname = "******";
$username = "******";
$dbname = "******";
$password = "*****";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
// Get values from form
$genre = $_POST['genre'];
$movie_name = $_POST['movie_name'];
$movie_text = $_POST['movie_text'];
$query = "INSERT INTO movies (ID, genre, movie_name, movie_text) VALUES
('$user_ID','$genre','$story_name','$story_text')";
$result = mysql_query($query);
if($result)
{
echo("
Entry Succesful");
}
}
else
{
echo("
failed to start");
}
?>
Get started!
<br><br>
<form name="movie" action="" method="post">
What type of movie? <select name="genre">
<option value="">Select...</option>
<option value="Comedy">Comedy</option>
<option value="Drama">Drama</option>
</select>
Name of Movie: <input type="text" size="55" name="movie_name">
<textarea rows="30" cols="80" name="movie_text" rows="4"></textarea>
<input type="submit" name="submit" id="submit" value="Add movie" />
</form>
hope this help :)

How to edit table values in MySQL and PHP?

I have that people can add team names to my MySQL table. Now I want them to edit it. I have tried several tutorials but i can't figure it out. I like to know what i am doing wrong.
This is my admin.php:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
if(isset($_POST['team'])){
$team = $_POST['team'];
$ID = $_POST['id'];
$query = mysql_query("SELECT * FROM e2teams WHERE Team='$team' and ID='$ID'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "$team bestaat al!";
}
else{
mysql_query("INSERT INTO e2teams (Team) VALUES ('$team')");
header("location:e2admin.php");
}
}
mysql_close();
?>
<html>
<body>
<h1>Add teams</h1>
<form action="e2admin.php" method="POST">
<input type="text" name="team" placeholder="Team naam" /><br>
<input type="submit" value="Toevoegen" />
</form>
<?php
$table = "e2teams";
$sql = "SELECT * FROM e2teams";
$result = mysql_query($sql, $dbhandle);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo $row['Team']. "<a href='edit.php?edit=$row[1]'>Bewerk</a><br>";
}
}
?>
</body>
</html>
The add teams works. but the edit button doesn't work yet. If I click on edit I go to the edit.php page; here I want to add the new name and need the Team to change in the MySQL row.
This is my edit.php:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
if( isset($_GET['edit'])) {
$id = $_GET['edit'];
$res = mysql_query("SELECT * FROM e2teams");
$row= mysql_fetch_array($res);
}
if (isset ($_POST['nieuwenaam'])) {
$newname = $_POST['nieuwenaam'];
$id = $_POST['id'];
$sql = "UPDATE e2teams SET Team='$newname' WHERE id='$id'";
$res = mysql_query($sql) or die ("Fout bij updaten".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=edit.php'>";
}
?>
<html>
<body>
<form action="edit.php" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" /><br>
<input type="hidden" name="id" placeholder="idnaam" value"s" /><br>
<input type="submit" value="Update" />
</form>
</body>
</html>
I also like to know how to delete team names but this is maybe for a next question.
This should work:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$id = intval($_GET['edit']);
if($id > 0) {
$res = mysql_query("SELECT * FROM e2teams WHERE `id` = $id");
$row= mysql_fetch_array($res);
$newname = mysql_real_escape_string($_POST['nieuwenaam']);
if (!empty($newname)) {
$sql = "UPDATE e2teams SET Team='$newname' WHERE id=$id";
$res = mysql_query($sql) or die ("Fout bij updaten".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=edit.php?edit=$id'>";
}
}
?>
<form action="edit.php?edit=<?= $id; ?>" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" /><br>
<input type="submit" value="Update" />
</form>
</body>
</html>
Edit: Also, about the intval() and mysql_real_escape_string(). Since you were using $_GET without any filter, I've added intval() function on it. Without filtering $id you could've been easily attacked by some sort of e.g. SQL Injection. Same with mysql_real_escape_string(). You might read about this filter function in php manual. For further study I recommend changing mysql_ functions to PDO or mysqli prepared statements. Happy coding!
Check your edit form. You have to put the value attribute like this value="s" no like value"". I think thats all.
I assume when they click on the edit link it's passing the id of the team so the edit.php select should be something like:
$id = (int)$_GET['edit'];
if (!empty($id))
{
$sql = "SELECT * FROM e2teams WHERE id='$id'";
$result = mysqli_query($sql);
$row = mysql_fetch_assoc($res);
}
//... keep the rest of code as is
Now you need to change the HTML form to:
<form action="edit.php?edit=<?php echo $row['id'] ?>" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" value="<?php echo $row['Team'] ?>" /><br>
<input type="hidden" name="id" placeholder="idnaam" value"<?php echo $row['id'] ?>" /><br>
<input type="submit" value="Update" />
</form>

Categories