I want to update data in my database using php loop.
I have tried updating data, but it only updates the last record in my list and returns all the records as null/zero.
// attempting to update data
$rcount_student_lists = mysqli_query($mysqli, $count_student_lists);
while($row2 = mysqli_fetch_row($rcount_student_lists))
$student_count_count = $row2['0'];
for ($id = 1; $id <=$student_count_count; $id++)
{
$sql = "UPDATE exam_data SET score_s = '".${'dd_'.$id}."' WHERE exam_name_s = '".$one."'";
}
if (mysqli_query($mysqli, $sql)) {
echo juuhead("DETAILS UPDATED SUCCESFULLY");
} else {
echo "Error updating record: " . mysqli_error($mysqli);
}
I would want it to update all the records in the column score_s
You're generating the SQL string in a loop:
for ($id = 1; $id <=$student_count_count; $id++)
{
$sql = ...;
}
But you're only executing it once, because this is outside the loop:
if (mysqli_query($mysqli, $sql)) {
Move the query command inside the loop:
for ($id = 1; $id <=$student_count_count; $id++)
{
$sql = ...
if (mysqli_query($mysqli, $sql)) {
...
} else {
...
}
}
You're also missing braces on your while loop:
while($row2 = mysqli_fetch_row($rcount_student_lists))
$student_count_count = $row2['0'];
Without braces, the while only loops the one line following it. To loop over more than one line, you need to wrap the lines in braces:
while($row2 = mysqli_fetch_row($rcount_student_lists))
{
$student_count_count = $row2['0'];
for ($id = 1; $id <=$student_count_count; $id++)
{
...
}
}
Also, please read about SQL injection. Instead of building queries with string concatenation, use prepared statements with bound parameters. See this page and this post for some good examples.
Related
I want to create a function that automatically makes a connection to the database and performs the given queries but I can't get it to work and it gives no errors.
I think I'm not outputting in the correct way my goal is to output a array that stores all the returned values from the queries.
Here is my code so far hope you can help:
public function db_query() {
$ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/app.ini');
$mysqli = new mysqli($ini['db_location'], $ini['db_user'], $ini['db_password'], $ini['db_name']);
// create string of queries separated by ;
$query = "SELECT name FROM mailbox;";
$query .= "SELECT port FROM mailbox";
// execute query - $result is false if the first query failed
$result = mysqli_multi_query($mysqli, $query);
if ($result) {
do {
// grab the result of the next query
if (($result = mysqli_store_result($mysqli, 0)) === false && mysqli_error($mysqli) != '') {
echo "Query failed: " . mysqli_error($mysqli);
while ($row = $result->fetch_row()) {
echo $row[0];
}
}
} while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results
} else {
echo "First query failed..." . mysqli_error($mysqli);
}
}
Note: I did not add the parameter for the query just for testing
purposes.
public function db_query($mysqli) {
$return = [];
$result = mysqli_query($mysqli, "SELECT name FROM mailbox");
while ($row = $result->fetch_row()) {
$return[] = $row[0];
}
$result = mysqli_query($mysqli, "SELECT port FROM mailbox");
while ($row = $result->fetch_row()) {
$return[] = $row[0];
}
return $return;
}
simple, clean, efficient, always works
I have a problem with my PHP code, I can't get it to delete some data inside my MySQL database. I have tried some different things but it just won't work.
What iv'e tried: Deleting $productId, switched $producId to 1, 2, 3 and 4.
if (isset($_POST['remove_product'])) {
$productId = 4
$sql = "DELETE FROM products WHERE id = '.$productId.'";
$stmt = mysqli_init($conn);
if (!mysqli_prepare($stmt, $sql)) {
header("Location: products.php?error=sqlerror");
exit();
} else {
mysqli_execute($stmt);
}
}
I would like if it could delete the data from the MySQL table, so if someone could come with a solution, thanks : )
Thanks!
You are using the wrong functions to initialise, prepare and execute your statement. You should be using mysqli_stmt_init, mysqli_stmt_prepare and mysqli_stmt_execute instead. Also, since you are preparing a statement, you should take advantage of that to avoid SQL injection. Try this:
if (isset($_POST['remove_product'])) {
$productId = 4;
$sql = "DELETE FROM products WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: products.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, 'i', $productId);
mysqli_stmt_execute($stmt);
}
}
You are lacking a semicolon
$productId = 4
--------------^
Use
$productId = 4;
You have some issues with quotation marks:
$sql = "DELETE FROM products WHERE id = '.$productId.'";
-------^--------------------------------^------------^^
It should say:
$sql = "DELETE FROM products WHERE id = " . $productId;
Also you are not using prepared statements in the right way
if (isset($_POST['remove_product'])) {
$productId = 4;
$sql = "DELETE FROM products WHERE id = ?";
if (!$stmt = mysqli_prepare($sql)) {
header("Location: products.php?error=sqlerror");
exit();
} else {
$stmt->bind_params("i", $productId);
$stmt->execute();
}
}
There are some syntactic mistakes in your code. Use mysqli-query to execute the the query. it is used frequently
if (isset($_POST['remove_product'])) {
$productId = 4;
$sql = "DELETE FROM products WHERE id = ".$productId;
$stmt = mysqli_init($conn);
if (!mysqli_query($stmt, $sql)) {
header("Location: products.php?error=sqlerror");
exit();
} else {
mysqli_execute($stmt);
}
}
try this once
[!]problem: whenever I get the data from frontend and try to insert into database...the data are inserted as a single alphabet in elective cell...but what I really needed that the whole data to be inserted in the elective cell with separated by comma(,)
<?php
include_once '../../config/db_connection.php';
include_once '../../config/functions.php';
include "autho.php";
include('../db_mysqli.php');
if (isset($_POST['submit'])) {
$username1 = $_POST['username'];
$username1 = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $username1);
$rollno = $_POST['register_no'];
$rollno = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $rollno);
$subjectcode = implode(',', $_POST['subject']); ;
date_default_timezone_set("Asia/Kolkata");
$today = date('g:ia \o\n l jS F Y');
$rollnos = array_map('strlen', $rollno);
$rollnos = min($rollnos);
if ($rollnos < 6) {
$error = 'Roll Number is too short.';
} else {
}
if (!isset($error)) {
for ($i = 0; $i < count($rollno); $i++) {
$sql = "UPDATE students SET elective='$subjectcode[$i]' WHERE register_number='$rollno[$i]'";
$result = mysqli_query($conn, $sql);
if ($result) {
header('Location:./?edu_camp=elective_student_update&success');
} else {
header('Location:./?edu_camp=elective_student_update&fail');
}
}
} else {
//echo "Sorry! something Wrong.";
}
}
?>
As the comments mentioned, you can implode your array into a string an insert it (docs).
Also, you're using MySQLi, but not using bound parameters which you REALLY should be using (docs).
// Concatenate all values together
$commaSeparatedList = implode(',',$subjectcode);
// Prepare your statement
$stmt = $mysqli->prepare("UPDATE students SET elective=? WHERE register_number=?");
// Bind the relevant parameters (not sure what the where clause should be here)
$stmt->bind_param('si', $commaSeparatedList, $i);
// Check if rows were affected
if ($mysqli->affected_rows > 0) {
// Success, rows were changed
}
// Execute and close the statement object
$stmt->execute();
$stmt->close();
I have to save more than one row of data into database table.
I wrote this code for that. But when i run this code, two rows will be saved into two rows of db table, but every other row is same as the last row data.
i.e. that is the last row data is overwriting every other row data.
$values = array();
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
You aren't resetting your values array inside the loop so values[0] and values[1] will always have the first to values.
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
$values = array();
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
On a sidenote I would recommend looking into the PDO extension and parameterised queries as mysql_ is deprecated and the above code is vulnerable to SQL injection
You are mixing mysql and mysqli:
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db("dbname");
if (mysqli_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
I'm preparing some statements and want to check if the row exists before I update. If it exists then update it, if it doesn't then output a message "No such animal". I have the update bit working, but unsure how to check if the row exists. Please assist.
$v = array();
$v[] = $_POST['status'];
$v[] = $_POST['id'];
$dbh = dbh_get();
$sql = 'UPDATE tap SET status=?
WHERE id =?';
$stmt = $dbh->prepare($sql);
$stmt->execute($v);
\\ if row isn't there display message "No such animal"
\\ otherwise print the below
printf("Status was changed to - %s", $v[0]);
\\then either way have my continue button for me to click on
print '<div class="button" style="float:left;" onclick="window.location.href=\'admin.php\';">Admin</div>' . "\n";
dbh_free($dbh)
According to your question, you want to check if the row exists before performing update. you can try this -
$id_exist = 0;
$sql = "SELECT id
FROM tap" ;
$sql_prepare = $dbh->prepare($sql);
$sql_prepare->execute();
while($row = $sql_prepare->fetchObject()) {
if($_POST['id'] == $row->id) {
$id_exist = 1;
}
}
if($id_exist == 1) {
// perform update here
} else {
echo 'No such animal';
}