update specific row based on user selection using PDO via php issue - php

I am trying to update my sql table based off user input. So the user picks from a select list the column they want to update. Then they enter the data from the row and then what they want to update that with. so say the pick column teamname, the would then enter the team name they want to change via text box and then via another textbox enter the new name. Thats what Im trying to get to happen anyways.
I tried to copy and paste my code from where the user deletes data and modify it. I have tried a couple different things, the first thing I tried gave me this error:
UPDATE teams SET rockets = :value1 WHERE teamname = rockets
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'rockets' in 'where clause'
My sql statement looked like this:
$sql = "UPDATE teams SET $selectData = :value1 WHERE $columnSelect = $selectData";
Then, I tried to do something like this:
entire code below, as stated above I have tried a couple different thigns with the $sql variable:
php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$columnSelect = $_POST['selectColumn2'];
$selectData = $_POST['selectData'];
$updateData = $_POST['updateData'];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to delete a record
$sql = "UPDATE teams SET :value1 = :value2 WHERE $columnSelect = :value1";
// use exec() because no results are returned
$stmt = $conn->prepare($sql);
$stmt->execute(array(':value1'=>$selectData, ':value2'=>$updateData));
if ($stmt->rowCount() > 0) {
echo 'Updated '.$stmt->rowCount().' rows';
} else {
echo 'No rows updated';
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
html
<form method='post' action='addData.php'>
Select a column name, then enter which data to update.
<br>
<br>
<label for='option2'>
<select name='selectColumn2'>
<option value='teamname' id='team2'>teamname</option>
<option value='city' id='city2'>city</option>
<option value='bestplayer' id='best2'>bestplayer</option>
<option value='yearformed' id='year2'>year</option>
<option value='website' id='website2'>website</option>
</select>
</label>
<label for='option2'>
select data to change: <input type='text' name='selectData'>
enter new data: <input type='text' name='updateData'>
</label>
<br><br>
<input type='submit' value='Submit New Entry'>
</form>
Basically what I what to do is take $columnSelect, find $selectData in that column and replace it with $updateData using the PDO method. What am I doing wrong?

This should work: UPDATE teams SET $columnSelect = :value1 WHERE $columnSelect = $selectData

Change your query like this,
$sql = "UPDATE teams SET `$selectData` = ':value1' WHERE `$columnSelect` = '$selectData'";
Add single quotes for string values while inserting or updating. And addd backtics for the table name or column names.
EDIT
$sql = "UPDATE teams SET `$columnSelect` = ':value1' WHERE `$columnSelect` = '$selectData'";

Related

Select individal colums when fetching data from a database

I've just started learning PHP so this is quite a struggle for me, any help is appreciated!
So, I've managed to select my database, table and get data from it. But I need to select more data from the older columns.
Here is some of the code:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//execute the SQL query and return records
$result = mysqli_query($conn, "SELECT username FROM interview");
while($rowval = mysqli_fetch_array($result))
{
$username= $rowval['username'];
$username2= $rowval['username'];
$username3= $rowval['username'];
$username4= $rowval['username'];
}
?>
And I am displaying the data in a button, I want $username to display the first column and $username2 to display the second column etc...
I fetch the data using this code:
<?php echo $username; ?>
<?php echo $username2; ?>
<?php echo $username3; ?>
<?php echo $username4; ?>
Thanks!
I would suggest you re-factoring your "while" loop the following way for better scalability:
$usernames=array();
while($rowval = mysqli_fetch_array($result))
{
$usernames[] = $rowval['username'];
}
Then, you'll be able to access usernames like:
echo 'The first user name is: '.$usernames[0];
echo 'The second user name is: '.$usernames[1];
echo 'The third user name is: '.$usernames[2];
My php skills are a bit rusty, so take this with a grain of salt:
At first it is important to get the language right. A database table consists of rows and columns, the columns are the ones you select with the the part after the SELECT statement, if you write SELECT username what you select is the username column.
SELECT username FROM interview;
So if you want to select more columns from your table you have to put them in your SELECT statement. Let's say you want to select the username and the status of the interview, you would need to include the status in your SELECT statement like this:
SELECT username, status from interview;
Then you can access the interview status just like you did it with the username.
$result = mysqli_query($conn, "SELECT username, status from interview;");
while($rowval = mysqli_fetch_array($result))
{
$username= $rowval['username'];
$status = $rowval['status'];
}
Remember that what you get as the $rowVal is just a single row of your table. So if you want to collect all usernames and statuses from your table you have to use a datastructure to collect them.
$queryResult = mysqli_query($conn, "SELECT username, status from interview;");
$result = array();
while($rowval = mysqli_fetch_array($queryResult))
{
$username= $rowval['username'];
$status = $rowval['status'];
// With this action we build an array, that has each row's result as value.
$result[] = array('username' => $username, 'status' => $status);
}
To access the results you can then query the $result array like this:
// The interview status of the first entry in your table
$result[0]['status'];

PHP MYSQL update stament not working

This code is meant to check the submitted form values and update the table,
however it just replaces the field with a blank
Any ideas where it is gone wrong, please?
<form action = "update.php" method = "POST">
<p>
New Name: <input type "text" name="name">
<input type= "submit">
</p>
</form>
<?php
require ('/var/www/html/site1/connect_db.php');
if(!empty($_POST['name']) && !is_numeric($_POST['name']))
{
$name=$_POST['name'];
$name=mysqli_real_escape_string($dbc,$query);
$name=strip_tags($name);
#$query='update customers SET customerName = '".$name."' where customerNumber=114';
$query = "update customers ". "SET customerName = $name"."where customerNumber=114" ;
mysqli_query($dbc,$query);
}
else
{
echo $name;
}
$query = 'select * from customers where customerNumber=103';
$result = mysqli_query($dbc,$query);
while ($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
echo"<p>Name : $row[1]</p>";
}
mysqli_close($dbc);
?>
You are updating customer number 114 but selecting 103 out, whose name may be blank.
Your update statement needs to have quotes around the $name bit as below:
$query = "UPDATE customers SET customerName = '$name' WHERE customerNumber=114";
Edit: please see the parameterised query advice in the question comments.

Disease-Symptom relation in MySQL

I am making an electronic health system related to patient diagnosing in PHP and MySQL. I have made following tables in database with the following records:
Illness(illness_id(PK), illness_code,illness_name)
Symptom(symptom_id, illness_id(FK),symptom_name ).
Now, what I would like to do is that, I will write name of symptom in search bar and after clicking button, related diseases should be output. Could you tell me SQL query that will output appropriate diseases please?
Please try this. After you retrieve the symptom value from the search bar into a variable, say symptom_name_provided_in_search_bar, you can use that value in the below query
select illness_name
from illness a, symptom b
where a.illness_id = b.illness_id
and b.symptom_name = :symptom_name_provided_in_search_bar
For this to work you should create only one table illness with 2 rows:
illnessName and illnessSymptom. Note: This will only work if the symptom is written exactly as in the database.
<?php
$host = 'yourmysqlhost';
$user = 'yourmysqluser';
$pass = 'yourmysqlpassword';
$db = 'yourmysqldatabase';
$symptom = $_POST['symptom'];
$connect = mysqli_connect($host, $user, $pass, $db);
$sanitizedSymptom = mysqli_real_escape_string($connect, $symptom);
$query = mysqli_query($connect, "SELECT * FROM illness WHERE illnessSymptom = '".$sanitizedSymptom."'");
if(mysqli_num_rows($query) == 0)
{
echo '<p>No results...</p>';
}
else
{
while($row = mysqli_fetch_assoc($query))
{
echo '<h1>'.$row['illnessName'].'</h1>';
echo '<p>Symptom: '.$row['illnessSymptom'].'</p>';
echo '<br>';
}
}
?>
Edit:
To find a symptom that is approximately like the symptom in the database, the query should be like this:
$query = mysqli_query($connect, "SELECT * FROM illness WHERE illnessSymptom LIKE '%".$sanitizedSymptom."%'");

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";
}

Insert data into table at one time

This is my code
echo '<input type="submit" name="submit">';
I am getting the data from another table with this query
if($_POST['submit'])
{
$sql = mysql_query('SELECT q.username, q.firstanme,q.lastname FROM quizgroup q');
foreach($sql as $s)
{
$username = $s->username;
$firstname = $s->firstname;
$lastname = $s->lastname;
$sql = mysql_query('INSERT INTO user(username,firstname,lastname) VALUES('.$username.','.$first.','.$last.')');
}
}
Try this
insert into user (SELECT username, firstanme, lastname FROM quizgroup)
This statement will copy the data from quizgroup to user table
Dont use "values" keyword when copy the data
Look at this
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

Categories