Database not updating with MYSQLI - php

I'm beginner at PHP and I'm using a tutorial I found on the web to work a new piece of a new CMS I'm building. The problem is that the tutorial works just fine but when I start to alter it to my use it cannot connect to the database to update. I receive my error "Database Error: Unable to update record." I can add and delete but not update.
Index.php
<html>
<head>
<title>MySQLi Tutorial</title>
</head>
<body>
<?php
//include database connection
include 'db_connect.php';
$action = isset($_GET['action']) ? $_GET['action'] : "";
if($action=='delete'){ //if the user clicked ok, run our delete query
$query = "DELETE FROM family WHERE fid = ".$mysqli->real_escape_string($_GET['fid'])."";
if( $mysqli->query($query) ){
echo "User was deleted.";
}else{
echo "Database Error: Unable to delete record.";
}
}
$query = "SELECT * FROM family";
$result = $mysqli->query( $query );
$num_results = $result->num_rows;
echo "<div><a href='add.php'>Create New Record</a></div>";
if( $num_results ){
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>name</th>";
echo "<th>Action</th>";
echo "</tr>";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$name}</td>";
echo "<td>";
echo "<a href='edit.php?fid={$fid}'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='delete_user( {$fid} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{
//if table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
<script type='text/javascript'>
function delete_user( fid ){
//this script helps us to
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and fid to the record to be deleted
window.location = 'index.php?action=delete&fid=' + fid;
}
}
</script>
</body>
</html>
add.php
<html>
<head>
<title>MySQLi Create Record</title>
</head>
<body>
<!--we have our html form here where user information will be entered-->
<form action='#' method='post' border='0'>
<table>
<tr>
<td>Firstname</td>
<td><input type='text' name='name' /></td>
</tr>
<td></td>
<td>
<input type='hidden' name='action' value='create' />
<input type='submit' value='Save' />
<a href='index.php'>Back to index</a>
</td>
</tr>
</table>
</form>
<?php
$action = isset($_POST['action']) ? $_POST['action'] : "";
if($action=='create'){
//include database connection
include 'db_connect.php';
//write query
$query = "insert into family
set
name = '" . $mysqli->real_escape_string($_POST['name']) ."'
";
if( $mysqli->query($query) ) {
echo "User was created.";
}else{
echo "Database Error: Unable to create record.";
}
$mysqli->close();
}
?>
</body>
</html>
edit.php
<?php
//include database connection
include 'db_connect.php';
$action = isset( $_POST['action'] ) ? $_POST['action'] : "";
if($action == "update"){
//write query
$query = "update users
set
name = '".$mysqli->real_escape_string($_POST['name'])."',
where
fid='".$mysqli->real_escape_string($_REQUEST['fid'])."'";
if( $mysqli->query($query) ) {
echo "User was updated.";
}else{
echo "Database Error: Unable to update record.";
}
}
$query = "select fid, name
from family
where fid='".$mysqli->real_escape_string($_REQUEST['fid'])."'
limit 0,1";
$result = $mysqli->query( $query );
$row = $result->fetch_assoc();
$fid = $row['fid'];
$name = $row['name'];
?>
<!--we have our html form here where new user information will be entered-->
<form action='#' method='post' border='0'>
<table>
<tr>
<td>Firstname</td>
<td><input type='text' name='name' value='<?php echo $name; ?>' /></td>
</tr>
<tr>
<td></td>
<td>
<!-- so that we could identify what record is to be updated -->
<input type='hidden' name='fid' value='<?php echo $fid ?>' />
<!-- we will set the action to edit -->
<input type='hidden' name='action' value='update' />
<input type='submit' value='Edit' />
<a href='index.php'>Back to index</a>
</td>
</tr>
</table>
</form>
>
I have been unable to find the proper language to fix this but I believe it's because I"m using some form of multiples but I am not familiar with the mysqli/php languages to fix it.
Thank you

You need to remove the comma at the end of:
name = '".$mysqli->real_escape_string($_POST['name'])."',
the query should be:
$query = "update users
set
name = '".$mysqli->real_escape_string($_POST['name'])."'
where
fid='".$mysqli->real_escape_string($_REQUEST['fid'])."'";

Related

How to update multiple rows in SQL table based on id using one button

table.php
<?php
include('../connections/conn.php');
include('../php/login.php');
$sql = "SELECT * FROM person";
$records = mysqli_query($conn, $sql)
?>
<html>
<head>
<title>Table</title>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Salary</th>
</tr>
<?php
while($row = mysqli_fetch_array($records)){
$name = $row['Name'];
$age = $row['Age'];
$salary = $row['Salary'];
$id = $row['id'];
echo "<tr><form action=update.php method=post>";
echo "<td><input type=text name=pname value='$name'></td>";
echo "<td><input type=text name=age value='$age'></td>";
echo "<td><input type=text name=salary value='$salary'></td>";
echo "<input type=hidden name=id value='$id'></td>";
echo "<td><input type=submit>";
echo "</form></tr>";
}
?>
</table>
</body>
</html>
(this part of the code displays the table and its values)
Update.php
<?php
include('../connections/conn.php');
include('../php/login.php');
$sql = "UPDATE person SET
Name='$_POST[pname]',Age='$_POST[age]',Salary='$_POST[salary]' WHERE
id='$_POST[id]'";
if(mysqli_query($conn, $sql)){
header("refresh:1 url=table.php");
}
else{
echo"Not Update";
}
$records = mysqli_query($conn, $sql)
?>
(this part is for updating the table)
I have got the code to update the contents of a table using buttons however I would like to just have one button that will update the whole table. At the moment I use a button per row to update that particular row.
Just use this
$sql = "UPDATE person SET
Name='$_POST[pname]',Age='$_POST[age]',Salary='$_POST[salary]' WHERE
id in('$_POST[id]')";

Link a href to result of PHP search script

I have a simple search script like this and works fine:
<html>
<head>
<title>any</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script>
function check() {
var searchtext = document.getElementById("txt").value;
if(searchtext == '') {
alert('Enter string to search');
} else {
document.myform.submit();
}
}
function reset_table() {
document.myform.submit();
}
</script>
</head>
<body>
<?php
error_reporting(0);
require_once "config.php";
$link = mysql_connect($hostname, $username, $password);
$dbcon = mysql_select_db($dbname);
echo "<div align='center' class='resp_code'>";
echo "<h5><b>...</b></h5>";
echo "<div align='center'>";
echo "<form method='post' action='index.php' id='searchform' class='frms' name='myform'>
<input type='text' id='txt' name='name' autocomplete='off'>
<input type='submit' name='submit' value='Search' id='search' onclick='check();'>
<input type='submit' name='reset' value='Reset' id='reset' onclick='reset_table()'>
</form> ";
echo "</div>";
echo "<div align='center'>";
$search = $_POST["name"];
if(isset($_POST['name'])) {
echo "<table class='table'>
<tr>
<th>No.</th>
<th>Un.</th>
<th>img</th>
</tr>";
$qry = mysql_query('SELECT * FROM rs_posts WHERE id like "%'.$search.'%"');
$count = mysql_numrows($qry);
if($count > 0) {
if($qry) {
while($row = mysql_fetch_row($qry)) {
$num = $row['id'];
$uniq = $row['unique_id'];
$img = $row['featured_img'];
echo "<tr>
<td id='num'>$row[0]</td>
<td id='uniq'>$row[1]</td>
<td id='img'>$row[25]</td>
</tr>";
}
} else {
echo "No";
}
} else{
$op = "No Results Found";
}
}
echo "</div>";
echo "<div style='font-weight:bold;color:red;'>$op</div>";
echo "</div>";
?>
</body>
</html>
and have a link code like this:
link
I need some of search results like
<td id='img'>$row[25]</td>
link to that. What's the most simple way to do that?
If accept alert or click on RESET button it show all content of my db but I need hide them when I don't input anything or click RESET button. How can resolve I that?

Can't display data from my DATABASE Server

<?php
//connection to the database
try {
$pdo = new PDO('mysql:host=localhost;dbname=frostedc_movies;charset=utf8',
frostedc_user, 'pass');
echo "connected";
}
catch(PDOException $e) {
echo $e; //2
}
// select everything from the news table
$query = "SELECT * FROM movie";// Table name NOT database name
foreach ($pdo->query($query) as $row) {
echo "<table border='1'>";
echo "<tr>";
echo "<td width='150'>".$row['movietitle']."</td>";
echo "<td width='150'>".$row['genre']."</td>";
echo "<td width='150'>".$row['LastViewed']."</td>";
echo "<td width='150'>".$row['Location']."</td>";
echo "</tr>";
}
echo "</tr>";
echo "</table>";
echo "<br>";
echo "
<form>
<p>Please Enter a Movie Title</p>
<input type='text' name='new_movie' />
<input type='submit' value='Submit' />
</form>";
echo "
<form>
<p>Please Enter the Genre</p>
<input type='text' name='movie_genre' />
<input type='submit' value='Submit' />
</form>";
echo "
<form>
<p>Please Enter the Last View Date</p>
<input type='text' name='last_view' />
<input type='submit' value='Submit' />
</form>";
echo "
<form>
<p>Please Enter the Location</p>
<input type='text' name='movie_loca' />
<input type='submit' value='Submit' />
</form>";
$pdo = null;
?>
this is the new updated code. I am trying to use the inputs to enter data into my database.
I have researched how to do this, but so far I haven't got anything to work. Any thoughts? Also would it be easier for me to use include and make the inputs in html? if so could i use them to enter the data into the db?
You are doing 2 wrong things here
First : Mixing PDO with MySQL
Second : $query = "SELECT * FROM myDB"; You cant select from a Database.. You need to do a SELECT from your TABLE ! (Are you sure myDB is your table ?)
As you have tagged your question PDO I have removed all unneeded code from your example.
<?php
//connection to the database
try {
$pdo = new PDO('mysql:host=localhost;dbname=frostedc_movies;charset=utf8',
user, 'password'); //1
echo "connected";
}
catch(PDOException $e) {
echo $e; //2
}
// select everything from the news table
$query = "SELECT * FROM myTable";// Table name NOT database name
echo "<table>";
echo "<tr>";
foreach ($pdo->query($query) as $row) {//3
echo "<td>".$row['movietitle']."</td>";
echo "<td>".$row['genre']."</td>";
echo "<td>".$row['LastViewed']."</td>";
echo "<td>".$row['Location']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
$pdo = null;//5
?>
The number comments
1 Setting character set Manual
2 Echoing error message only for development.In production you should either do something with it or remove try/catch.
3 As there are no parameters use query()
4 For utf8 Prior to PHP 5.3.6
5 Changed mysql_close();(mysql_) to $pdo = null; (PDO)
<?php // connect to the database
$host = 'localhost';
$username = 'user';
$pass = 'password';
$conn=mysql_connect($host,$username,$pass)or die(mysql_error());
mysql_select_db("myDB");
// select everything from the news table
$query = "SELECT * FROM news";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<table>
<tr>
<td>".$row['movietitle']."</td>
<td>".$row['genre']."</td>
<td>".$row['LastViewed']."</td>
<td>".$row['Location']."</td>
</tr>
</table>";
}
// disconnect from the database
mysql_close();
?>
try this code
<?php // connect to the database
$host = 'localhost';
$username = 'user';
$pass = 'password';
mysql_connect($host,$username,$pass);
mysql_select_db("myDB");
// select everything from the news table
$query = "SELECT * FROM `tablename`";
$result = mysql_query($query);
echo "<table>";
echo "<tr>";
while( ($row = mysql_fetch_array($result)))
{
echo "<td>".$row['movietitle']."</td>";
echo "<td>".$row['genre']."</td>";
echo "<td>".$row['LastViewed']."</td>";
echo "<td>".$row['Location']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
mysql_close();
?>

PHP Edit/Delete multiple rows in mysql

Good evening, I'm trying to make a single php page wich can edit/delete multiple rows in mysql:
<html>
<head>
<title>Update/Delete Test Page</title>
</head>
<body>
<?
include 'connect.php';
if(isset($_POST['edit'])) // from button name="delete"
{
$title = $_POST['title'];
$description = $_POST['description'];
if(!empty($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $check) {
$ed = $check;
$sql = "UPDATE events SET title = '$title', description ='$description' WHERE id = $ed";
}
}
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
}
?>
<?php
include ("connect.php");
if(isset($_POST['delete'])) // from button name="delete"
{
if(!empty($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $check) {
$del = $check;
$sql = "DELETE from events where id = $del";
$result = $mysqli->query($sql) or die(mysqli_error($mysqli));
}
}
?>
<?php
include 'connect.php';
$query = 'SELECT id, title, description FROM events WHERE evdate = "1/9/2013" order by title asc';
$result2 = $mysqli->query($query) or die(mysqli_error($mysqli));
echo '<br><br><br>';
echo '<b><div align="center"> "1/9/2013"</div></b>';
if ($result2) {
// create a new form and then put the results
// into a table.
echo "<form method='post' action=".$_SERVER['PHP_SELF'].">";
echo "<table cellspacing='0' cellpadding='3'>
<th align='left'>Interval orar</th>
<th align='left'>Eveniment</th>
<th align='left'></th>
";
while ($row = $result2->fetch_object()) {
$title = $row->title;
$description = $row->description;
$id = $row->id;
//put each record into a new table row with a checkbox
echo "
<tr>
<td align='left'><input type='text' name='title' size='20' value='$title'></td>
<td align='left'><input type='text' name='description' size='50' value='$description'></td>
<td align='left'><input type='checkbox' name='checkbox[]' id='checkbox[]' value=$id />
</tr>
";
}
// when the loop is complete, close off the list.
echo "</table>
<p>
<input id='edit' type='submit' class='button' name='edit' value='Edit'/>
<input id='delete' type='submit' class='button' name='delete' value='Delete'/>
</p>
</form>";
}
?>
</body>
</html>
Connect.php looks like this:
<?php
$db_host = "localhost";
$db_username = "calendar";
$db_pass = "calendar";
$db_name = "ecalendar";
$con = mysql_connect ("$db_host", "$db_username", "$db_pass") or die ("could not connect to mysql database");
mysql_select_db("$db_name") or die ("no database");
$mysqli = new MySQLi($db_host, $db_username, $db_pass, $db_name) or die(mysqli_error());
?>
The delete works fine, but the edit doesn't do anything...
Table looks like this:
Start/End Time Event (Checkbox is here)
08:00-10:00 test1 X
10:00-12:00 test2 X
When I try to edit test2 to test2xx I get this in Firebug POST :
title=08%3A00-10%3A00&description=test1&title=10%3A00-12%3A00&description=test2xx&checkbox%5B%5D=53&edit=Edit
If I delete I get this (and it works)
title=08%3A00-10%3A00&description=test1&title=10%3A00-12%3A00&description=test2&checkbox%5B%5D=53&delete=Delete
Edit works but only for the last row (test2), if I try to edit the row above (test1), it insted updates it with the values of the last row (test2)
Guess you need del_id not id
$sql = "UPDATE events SET title = '$title', description ='$description' WHERE id = $del_id ";
1-look your value value=$id in your chekbob
change it to value= '$id'
2-and also , the delete query is with mysqli
but the update query is with mysql ??
3- u dont have to include connect.php 3 times
4- also what previous answer about the variable $del_id.
5- u are missing closing tag td
6- u are missing closing }
7- try this
<html>
<head>
<title>Update/Delete Test Page</title>
</head>
<body>
<?php
include 'connect.php';
if(isset($_POST['edit'])) // from button name="edit"
{
$checkbox = $_POST['checkbox']; //from name="checkbox[]"
$countCheck = count($_POST['checkbox']);
for($i=0;$i<$countCheck;$i++)
{
$del_id = $checkbox[$i];
$sql3 = "UPDATE events SET title = '$title', description ='$description' WHERE id = '$del_id' ";
$result3 = $mysqli->query($sql3) or die(mysqli_error($mysqli));
if (!$result3)
{
die(mysqli_error($mysqli)) ;
}
echo "1 record added";
}
}
if(isset($_POST['delete'])) // from button name="delete"
{
$checkbox = $_POST['checkbox']; //from name="checkbox[]"
$countCheck = count($_POST['checkbox']);
for($i=0;$i<$countCheck;$i++)
{
$del_id = $checkbox[$i];
$sql = "DELETE from events where id = '$del_id' ";
$result = $mysqli->query($sql) or die(mysqli_error($mysqli));
}
}
$query = 'SELECT id, title, description FROM events WHERE evdate = "1/9/2013" order by title asc';
$result2 = $mysqli->query($query) or die(mysqli_error($mysqli));
echo '<br><br><br>';
echo '<b><div align="center"> "1/9/2013"</div></b>';
if ($result2) {
// create a new form and then put the results
// into a table.
echo "<form method='post' action=".$_SERVER['PHP_SELF'].">";
echo "<table cellspacing='0' cellpadding='3'>
<th align='left'>Interval orar</th>
<th align='left'>Eveniment</th>
<th align='left'></th>
";
while ($row = $result2->fetch_object()) {
$title = $row->title;
$description = $row->description;
$id = $row->id;
//put each record into a new table row with a checkbox
echo "
<tr>
<td align='left'><input type='text' name='title' size='20' value='$title'></td>
<td align='left'><input type='text' name='description' size='50' value='$description'></td>
<td align='left'><input type='checkbox' name='checkbox[]' id='checkbox[]' value='$id' /></td>
</tr>
";
}
// when the loop is complete, close off the list.
echo "</table>
<p>
<input id='edit' type='submit' class='button' name='edit' value='Edit'/>
<input id='delete' type='submit' class='button' name='delete' value='Delete'/>
</p>
</form>";
}
?>
</body>
</html>
id=$del_id under for loop,double check your SQL statements and variables bound to them.
gave up on the code above and went with this example from
http://bohemiawebsites.com/PHP-MYSQL-Update-Multiple-Rows.html
Everything works if anybody needs it...

Link (on a while loop on a search query) inside a search form

echo "<center><form name = 'searching' method='POST' action='cpanel.php?manage=".$useraccounts."&rcad=".$viewcustomer."'><table border = 1>";
echo "<select name = 'filter'>";
echo "<option value ='username'>Username</option>";
echo "<option value ='username'>Username</option>";
echo "</select>";
echo " <input name='search' type='text' > ";
echo "<input type='submit' name='submit' value='Search'> ";
echo "<input type='submit' name='back' value='Back'><br><br>";
echo "<tr>";
echo "<td>User ID</td>";
echo "<td>Username</td>";
echo "<td>Last Name</td>";
echo "<td>First Name</td>";
echo "<td>Middle Initial</td>";
echo "<td>Address</td>";
echo "<td>Contact Number</td>";
echo "<td>Birthday</td>";
echo "<td>Date Registered</td>";
echo "<td> </td>";
echo "</tr>";
$submit = $_POST['submit'];
if(isset($submit)) {
$search = $_POST['search'];
$filter = $_POST['filter'];
include "dbconnect.php";
if ($search != NULL) {
$searchquery = mysql_query("SELECT * FROM register WHERE $filter LIKE '%$search%'");
while($fetchres = mysql_fetch_array($searchquery)) { //show search results
$userid = $fetchres['userid'];
$username = $fetchres['username'];
$lname = $fetchres['lname'];
$fname = $fetchres['fname'];
$mi = $fetchres['mi'];
$address = $fetchres['address'];
$contact = $fetchres['contact'];
$month = $fetchres['month'];
$day = $fetchres['day'];
$year = $fetchres['year'];
$dateregistered = $fetchres['date'];
$sendmessage = "<a href = 'cpanel.php?manage=".$useraccounts."&rcad=".$viewcustomer."&user=".$username."'>Send message</a>";
echo "<tr>";
echo "<td>$userid</td>";
echo "<td>$username</td>";
echo "<td>$lname</td>";
echo "<td>$fname</td>";
echo "<td>$mi</td>";
echo "<td>$address</td>";
echo "<td>$contact</td>";
echo "<td>$month $day, $year</td>";
echo "<td>$dateregistered</td>";
echo "<td>$sendmessage</td>";
echo "</tr>";
echo "$table";
if (isset($sendmessage)) {
$getuser = $_GET['user'];
if ($getuser == $username) {
//start send message
$touser = $username;
$fromuser = $adminsess;
$subject = $_POST['subject'];
$message = $_POST['message'];
$submit = $_POST['submit'];
$date = date("Y-m-d");
$rand = rand(98765432,23456789);
$table = '<center><script type="text/javascript" src="/js/sendmessage.js"></script>
<form action="cpanel.php?manage='.$useraccounts.'&rcad='.$viewcustomer.'&user='.$username.'&send='.$one.'" method="post" name="sendpm" onsubmit="return valid()">
<table>
<tr>
<td>
To:
</td>
<td>
'.$touser.'
</td>
</tr>
<tr>
<td>
Subject:
</td>
<td>
<input type="text" name="subject" id="subj1" />
</td>
</tr>
<tr>
<td>
Message:
</td>
<td>
<textarea name="message" cols="60" rows="10" id="mes1"></textarea>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name = "submit" value="Submit" />
</td>
</tr>
</table>
</form></center>';
if (isset($submit))
{
$send = $_GET['send'];
if ($send == $one) {
include "maildbconnect.php";
$query = mysql_query("INSERT INTO mailtbl_admin VALUES ('', '$touser', '$fromuser', '$subject',
'$message', '0', '0', '1', '$date', '$rand')");
echo "Message successfully sent.";
}
}
}//end send message
}//end $getuser
}
}
The form for sending a message ($table) doesn't appear after clicking the link ($sendmessage) on a certain search result. After clicking the link, i'm prompted to an empty table (table not inside the while loop) but the $_GET function is working. Can anyone tell me how to fix this? thanks a lot
$submit wont be set when following the link. So any code after:
if(isset($submit)) {
Will not fire.
You've got a lot wrong with this form. First off, you forgot a <tr> and <td> after your <table> tag.
echo "<center><form name = 'searching' method='POST' action='cpanel.php?manage=".$useraccounts."&rcad=".$viewcustomer."'><table border = 1><tr><td colspan='10'>";
echo "<select name = 'filter'>";
echo "<option value ='username'>Username</option>";
echo "<option value ='username'>Username</option>";
echo "</select>";
echo " <input name='search' type='text' > ";
echo "<input type='submit' name='submit' value='Search'> ";
echo "<input type='submit' name='back' value='Back'><br><br>";
echo "</td></tr>";
Alternatively you could move the opening <table> tag below the <select> tag.
After you fix that, try moving the logic where you insert the values into mailtbl_admin outside of the loop. I'm guessing you're only going to want to send the message to one user, so it only makes sense to move it out of the loop.

Categories