update while and php - php

Friends, I show the field name as the value 1 of the database and the value as the result of the field, but I can not raise it to save the value of the field.
$result = $db->query($query);
while($rowID = $result->fetchArray() ){
echo
" <label class=\"control-label \" for=\"text\">
".$row['value1'] ."
</label>
<input class=\"form-control\" value=".$rowID['value2'] ." id=\"\" name=".$rowID['id']." type=\"text\"/>
</div>";
}
if( isset($_POST['submit_data']) ){
$ret1 = $db->query($query);
while($rowID = $ret1->fetchArray())
{
$query = "UPDATE table set value2 ='" . $_POST[$rowID['id']] . "' WHERE id='" . $rowID['id'] . "'";
}
if( $db->exec($query) ){
$message = "Data is updated successfully.";
}else{
$message = "Sorry, Data is not updated.";
}
}

Your last generated value in while loop will be value of $query. you should execute query at same time.
if( isset($_POST['submit_data']) ){
$ret1 = $db->query($query);
while($rowID = $ret1->fetchArray())
{
$query = "UPDATE table set value2 ='" . $_POST[$rowID['id']] . "' WHERE id='" . $rowID['id'] . "'";
if( $db->exec($query) ){
$message = "Data is updated successfully.";
}else{
$message = "Sorry, Data is not updated.";
}
}
}

Related

How to update database's value after pressing button?

I am currently working on my assignment, I am trying to create a ban system for users, I wanna update the value of Deleted in my database to 1 whenever I press the submit button, I tried many on youtube videos but has not given any process
$id = $_SESSION['UserID'];
$query = "SELECT * FROM Users WHERE UserID='$id'";
$result = mysqli_query($link, $query);
$row2 = mysqli_fetch_assoc($result);
if ($row2['Admin'] == 0) {
echo '<div class="alert alert-warning" role="alert">
Unfortunately you do not have access to this page
</div>';
}
else {
$query = " SELECT * FROM Users WHERE Admin = 0";
$result = mysqli_query($link, $query);
echo '<div class="container">';
echo '</div>';
echo '<div class="container"><table class="table table-primary table-hover">';
echo '<tr><th>' . 'NameID' . '</th><th>' . 'Name' . '</th><th>' . 'Email' . '</th><th>' . '</tr>';
while ($row2 = mysqli_fetch_assoc($result)) {
echo '<tr><td>' . $row2['UserID'] . ' </td><td> ' . $row2['FirstName'] . ' ' . $row2['LastName'] . ' </td><td> ' . $row2['EMail'] . ' </td><td> '
. '<input type="submit" name="submit" class="btn btn-primary btn-xs" value="BAN">' . ' </td></tr>';
}
if (isset($_POST['submit'])) {
echo '</table>' . '</div>';
$id = $_SESSION['UserID'];
$query = "SELECT * FROM Users WHERE UserID='$id'";
$result = mysqli_query($link, $query);
if ($_POST['submit']) {
$query2 = "UPDATE `Users` SET `Deleted` = '1' WHERE `Users`.`UserID` ='$id'";
}
}
}
You define $query2 but never execute it. This is a common mistake.
Tip: Don't declare SQL as strings and then run it later, get in the habit of supplying the query as a direct argument to prepare().
For example:
$stmt = $link->prepare('UPDATE `Users` SET `Deleted` = '1' WHERE `Users`.`UserID`=?');
$stmt->bind_param('i', $id);
$stmt->execute();
You don't run the $query2, do it like this
if ($_POST['submit']) {
$query2 = "UPDATE `Users` SET `Deleted` = '1' WHERE `Users`.`UserID` ='$id'";
mysqli_query($link, $query2);
}

simplify php/mysql nested calls

I have a mysql table which I'm trying to turn into jQuery listview widgets. The part that I'm having trouble with is how best to extract the info from the table without doing multiple queries on the db itself. I have the following code which works:
global $conn;
$sql = "SELECT `id` FROM `implantFamilies` WHERE `familySelector` = '" . $_POST['implantFamily'] . "'"; //need to sanitise this
$result = $conn->query($sql);
if ($result->num_rows == 1) {
while($row = $result->fetch_assoc()) {
$familyId = $row["id"];
}
} else {
die("Error: " . $result->num_rows . " family groups in result. Alert administrator.");
}
?>
<form class="ui-filterable">
<input id="filterBasic-input" data-type="search">
</form>
<?php
$sql = "SELECT DISTINCT `familySection` FROM `implants` WHERE `familyGroupId` = '" . $familyId . "'";
$sections = $conn->query($sql);
if ($sections->num_rows > 0) {
while ($sectionRow = $sections->fetch_assoc()) {
$output .= "<b>" . $sectionRow["familySection"] . "</b><br>";
//DISPLAY COLLAPSIBLE DIV HERE
$sql = "SELECT DISTINCT `sectionHeading` FROM `implants` WHERE `familyGroupId` = '" . $familyId . "' AND `familySection` = '" . $sectionRow["familySection"] . "'";
$dividers = $conn->query($sql);
if ($dividers->num_rows > 0) {
while ($headingRow = $dividers->fetch_assoc()) {
$output .= "<i>" . $headingRow["sectionHeading"] . "</i><br>";
//DISPLAY list-divisers DIV HERE
$sql = "SELECT `reference`, `description`, `filterText`, `requiresLot` FROM `implants` WHERE `familyGroupId` = '" . $familyId . "' AND `familySection` = '" . $sectionRow["familySection"] . "' AND `sectionHeading` = '" . $headingRow["sectionHeading"] . "'";
$implants = $conn->query($sql);
if ($implants->num_rows > 0) {
while ($implantRow = $implants->fetch_assoc()) {
$output .= $implantRow["description"] . "<br>";
//DISPLAY implants DIV HERE
}
} else {
$output = "0 results";
}
}
} else {
$output = "0 results";
}
}
} else {
$output = "0 results";
}
$conn->close();
echo $output;
On the first lot of (simple) data which I've put into the table, this code executes 23 mysql queries. There must be a simpler way!

Can't display database records

I want to echo sql database records in my page and I am using this code. When I run it doesn't display the result from the db. I have records in the database that match the criteria. I am new in php and sql so please tell where I have mistakes.
session_start();
if (!isset($_SESSION['name'])) {
header('Location:vhod.php');
exit;
}
$pageTitle = 'СЪОБЩЕНИЯ';
include 'includes/header.html';
$email = $_SESSION['email'];
$name = $_SESSION['name'];
include 'php/db_connect.php';
$msgs = '';
$query = 'SELECT `timestamp`, `to`, `sender`, `subject`, `msg` FROM msg WHERE `to`="$name"';
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$msgs = "ДАТА: " . $row["timestamp"] . " >> От: " . $row["sender"] . " >> Тема: " . $row["subj"] . " >> Съобщение: " . $row["msg"] . "<br>";
}
} else {
$msgs = "Нямате съобщения :(";
}
try modifying the lower part of your code like this.
$msgs = '';
$query = "SELECT * FROM msg WHERE to=$name";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$msgs = "ДАТА: " . $row['timestamp'] . " >> От: " . $row['sender'] . " >> Тема: " . $row['subj'] . " >> Съобщение: " . $row['msg'] . "<br>";
}
} else {
$msgs = "Нямате съобщения :(";
}

PHP cannot insert data

When I using the following code I cannot insert data. It shows the following error message:
[An error occured while inserting your data. Please try again later.You have an error in your SQL syntax: check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 10]
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
$result = mysql_query($sql);
if(!$result)
{
echo 'Error while selecting from database. Please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
//there are no categories, so a topic can't be posted
if($_SESSION['userlevel'] == 1)
{
echo 'You have not created categories yet.';
}
else
{
echo 'Before you can post a topic, you must wait for an admin to create some categories.';
}
}
else
{
echo '<form method="post" action="">
Subject: <input type="text" name="topic_subject" />
Category:';
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select>';
echo 'Message: <textarea name="post_content" /></textarea>
<input type="submit" value="Create topic" />
</form>';
}
}
}
else
{
//start the transaction
$query = "BEGIN WORK;";
$result = mysql_query($query);
if(!$result)
{
//Damn! the query failed, quit
echo 'An error occured while creating your topic. Please try again later.';
}
else
{
//the form has been posted, so save it
//insert the topic into the topics table first, then we'll save the post into the posts table
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ",
" . $_SESSION['userid'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your data. Please try again later.' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicid = mysql_insert_id();
$sql = "INSERT INTO
posts(post_content,
post_date,
post_topic,
post_by)
VALUES
('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . $topicid . ",
" . $_SESSION['userid'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your post. Please try again later.' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
$sql = "COMMIT;";
$result = mysql_query($sql);
//after a lot of work, the query succeeded!
echo 'You have successfully created your new topic.';
}
}
}
}
`
You missed to add quotes around each string:
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(),
'" . mysql_real_escape_string($_POST['topic_cat']) . "',
'" . $_SESSION['userid'] . "'
)";
You have to add single quotes around your second mysql_real_escape_string. (And also around your $_SESSION['userid'] if it contains a string.)
<pre>
<?php
$con = mysql_connect( 'localhost', 'root','' );
if (!$con)
{
die( 'Could not connect: ' . mysql_error() );
}
mysql_select_db( "stack",$con );
$_SESSION['userlevel']= 1;
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
$result = mysql_query($sql);
if(!$result)
{
echo 'Error while selecting from database. Please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
//there are no categories, so a topic can't be posted
if($_SESSION['userlevel'] == 1)
{
echo 'You have not created categories yet.';
}
else
{
echo 'Before you can post a topic, you must wait for an admin to create some categories.';
}
}
else
{
echo '<form method="post" action="">
Subject: <input type="text" name="topic_subject" />
Category:';
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select>';
echo 'Message: <textarea name="post_content" /></textarea>
<input type="submit" value="Create topic" />
</form>';
}
}
}
else
{
//start the transaction
$query = "BEGIN WORK;";
$result = mysql_query($query);
if(!$result)
{
//Damn! the query failed, quit
echo 'An error occured while creating your topic. Please try again later.';
}
else
{
$user =1;
//the form has been posted, so save it
//insert the topic into the topics table first, then we'll save the post into the posts table
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ", ". $user. "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your data. Please try again later.' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicid = mysql_insert_id();
$sql = "INSERT INTO
posts(post_content,
post_date,
post_topic,
post_by)
VALUES
('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . $topicid . ",1
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your post. Please try again later.' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
$sql = "COMMIT;";
$result = mysql_query($sql);
//after a lot of work, the query succeeded!
echo 'You have successfully created your new topic.';
}
}
}
}
?>
</pre>
i am using same script and it is working. please check your session if it creates
Your sql query is breaking here enclose your string and date values with "'"
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(), <--- enclose with ."'"

Else statement doesn't work in option select

I am trying to implement a dropdown search option. All my search results are working. All the commands that I have assigned to if statements work, but when it does to else it deosn't work.
Here is my code:
if(isset($_REQUEST['submit'])){
$opt = $_POST['opt'];
if($opt==1){//if opt = 1
$sqle = "SELECT * FROM tbl_events WHERE title LIKE '%{$keywords}%'";
$resulte = mysql_query($sqle,$con) or die(mysql_error());
while($row=mysql_fetch_array($resulte)){
echo "<h4>" . $row['title'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}else if($opt==2){//if opt = 2
$sqls = "SELECT * FROM tbl_games WHERE games_name LIKE '%{$keywords}%'";
$results = mysql_query($sqls,$con)or die(mysql_error());
while($row=mysql_fetch_array($results)){
echo "<h4>" . $row['games_name'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}else{
echo "Your Searched keyword did not match";
}
}
What to do?
Try this: Take a flag to check if record exists.
$flag = false;
if($opt==1){//if opt = 1
$sqle = "SELECT * FROM tbl_events WHERE title LIKE '%{$keywords}%'";
$resulte = mysql_query($sqle,$con) or die(mysql_error());
if(mysql_num_rows($resulte) > 0) {
$flag = true;
while($row=mysql_fetch_array($resulte)){
echo "<h4>" . $row['title'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}
}else if($opt==2){//if opt = 2
$sqls = "SELECT * FROM tbl_games WHERE games_name LIKE '%{$keywords}%'";
$results = mysql_query($sqls,$con)or die(mysql_error());
if(mysql_num_rows($resulte) > 0) {
$flag = true;
while($row=mysql_fetch_array($results)){
echo "<h4>" . $row['games_name'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}
}
if(!$flag){
echo "Your Searched keyword did not match";
}

Categories