Switched computers and get two new mysqli_fetch_row errors. - php

after I managed to connect my website form to my database, I decided to try to transfer over my files to my work computer.
Initially I only had one error: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in...
However now I get an extra mysqli_fetch_row() error the same as above but the error is on a different line.
Additionally I also get the error: Undefined index: fill which I never got before. Are there any mistakes in my code? The form still works and can connect to my database.
<center><form action="fill.php" method="post">
Fill
<input type="text" id="fill"" name="fill">
<input type="submit" id ="submit" name="submit" value="Submit here!">
</form></center>
</div>
<?php
$val1 = $_POST['fill'];
$conn = mysqli_connect('localhost', 'root', '')or
die("Could not connect");
mysqli_select_db($conn, 'rfid');
$val2 = "SELECT * FROM card_refill WHERE refill = $val1";
$result1= $conn->query($val2);
$row = mysqli_fetch_row($result1);
$refill1 = $row[2];
$value = "SELECT *FROM card_credit ORDER BY id DESC LIMIT 1:";
$result = $conn->query($value);
$row = mysqli_fetch_row($result);
$refill = $row[2];
$money= $refill+$refill1;
echo $money;
$sql = "UPDATE card_credit SET value = '$money'";
if ($conn->query($sql) === TRUE) {
echo "Success";
}
else {
echo "Warning: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
</body>
</html>

You're getting that error because you use $_POST['fill'] without checking whether it's set first. It will only be set when the form is submitted, not when the form is first displayed. You need to put all the code that processes the form input into:
if (isset($_POST['submit'])) {
...
}
BTW, you can do that entire update in a single query.
UPDATE card_credit AS cc
CROSS JOIN card_refill AS cr
CROSS JOIN (SELECT * FROM card_credit ORDER BY id DESC LIMIT 1) AS cc1
SET cc.value = cr.col2 + cc1.col2
WHERE cr.refill = '$val1'

Like GolezTrol said from his comment. You're mixing object and functional notation.
Although this might not work exactly how you need it to because I don't have all the information. I have written you something I think is close to what you're looking for.
<?php
// Define the below connections via $username = ""; EXTRA....
// This is best done in a separate file.
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$val1 = $_POST['fill'];
$result1 = $conn->query("SELECT * FROM card_refill WHERE refill = '$val1' ");
$result2 = $conn->query("SELECT * FROM card_credit ORDER BY id DESC LIMIT 1:");
$refill1 = array(); // Pass Results1 Into Array
while($row = $result1->fetch_assoc()) {
$refill1[] = $row[2];
}
$refill = array(); // Pass Results2 Into Array
while($row = $result2->fetch_assoc()) {
$refill[] = $row[2];
}
/* Without an example of what data you are getting from your tables you will have to figure out what data you want from the arrays.
$money= $refill+$refill1;
echo "DEBUG: $money";
*/
// This code will not be functional until your populate the $money value.
$sql = "UPDATE card_credit SET value = '$money' ";
if ($conn->query($sql) === TRUE) {
echo nl2br("Record updated successfully"); // DEBUG
print_r(array_values($refill1)); // DEBUG
print_r(array_values($refill)); // DEBUG
echo nl2br("\n"); // DEBUG
} else { // DEBUG
echo "Error updating record: " . $conn->error; // DEBUG
echo nl2br("\n"); // DEBUG
}
$conn->close();
?>

Related

How can I make elements on my webpage automatically update when it's MySQL database changes?

I've created the following PHP code to produce a feed of all the comments in my MySQL database.
<?
$con = mysqli_connect("localhost","username","password","databasename");
if (!$con)
{
die('Could not connect: ' . mysqli_connect_error());
}
$query = "SELECT * FROM tablename ORDER BY timestamp DESC LIMIT 0 , 1000";
$comments = mysqli_query($con, $query);
echo "<h1>Recent Posts</h1><br><br><hr>";
while($row = mysqli_fetch_array($comments, MYSQLI_ASSOC))
{
$comment = $row['comment'];
$timestamp = $row['timestamp'];
$comment = htmlspecialchars($row['comment'],ENT_QUOTES);
$score = $row['score'];
$id = $row['id'];
echo " <div class='card'>
<p>$comment</p><br />
<p>Post #$id</p>
<p>Score: $score</p><br>
<button onclick='myfunction($id,1)'>Upvote</button><button onclick='myfunction($id,-1)'>Downvote</button><br>
<p style='color: grey'>$timestamp</p><hr>
</div>
";
}
mysqli_close($con);
?>
It is included within a HTML file which contains the following js script:
function myfunction(postid,vote){
$.ajax({
type: "POST",
url: 'addvote.php',
data: {vote: vote, postid: postid, score: $("#postscore").val()},
success: function(data){
alert(data);
}
});
}
Where the file addvote.php is given by the following code:
<?php
$con = mysqli_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysqli_connect_error());
}
$vote = $_POST['vote'];
$postid = $_POST['postid'];
$userid = $_SERVER['REMOTE_ADDR'];
$query2 = mysqli_query($con,"SELECT score FROM database.table WHERE id ='$postid'");
$row = mysqli_fetch_array($query2, MYSQLI_ASSOC);
$score = mysqli_real_escape_string($con,$row['score']);
$newscore = $score + $vote;
$query1 = mysqli_query($con,"SELECT * FROM database.table WHERE postid='$postid' AND ipaddress='$userid'");
$numi = mysqli_num_rows($query1);
if($numi == 0){
$query3 = "INSERT INTO `database`.`table` (`postid`, `ipaddress`, `vote`, `id`) VALUES ('$postid', '$userid', '$vote', NULL)";
mysqli_query($con, $query3);
$sql = "UPDATE `database`.`table` SET `score` = '$newscore' WHERE `mainfeed`.`id` = '$postid'";
mysqli_query($con, $sql);
echo "Thanks for voting!";
}
else {
echo "You have already voted on post number ".$postid;
}
mysqli_close($con);
?>
This all works fine when it comes up upvoteing and downvoting posts - it makes the change to the post score in the MySQL database without refreshing the webpage. However, it does not change the score shown on the webpage until the page is reloaded. How can I make it so that changes in the score are immediately displayed on the webpage, without needing to refresh it?
Thanks in advance
I've managed to solve this problem by changing the value of the variable data in the php script to the new value of the posts score. I've then used
document.getElementById('score').innerHTML = data;
So that the client side value changes to the value in the MySQL database, without having to fetch it.

How to UPDATE only filled input with a submit button?

PROBLEM: I got a problem updating my input into sql using PHP, the PHP updates all empty values into sql which I don't want to.
ACHIEVEMENT: So I hope to achieve when user submit their data either empty or filled then PHP might be able to pickup and update only filled data into my sql. I tried using input with value=">php echo here<" but it won't work with textarea, so I couldn't find any solution since I'm new to PHP and SQL. Tried to find similar posts but I couldn't make them work like I wanted to :(
<?php include 'config/sqlconnect.php'; ?>
<form method="post" action"config/sqlconnect.php">
</p>MainPage info</p>
<input type="text" name="mainPageInfo"/>
<br>
</p>MiddlePage info</p>
<textarea name="middlePageInfo"></textarea>
<br>
</p>Container info</p>
<input type="text" name="containerInfo"/>
<br>
</p>Content</p>
<input type="text" name="content"/>
<br>
</p>Second content</p>
<input type="text" name="secondContent"/>
<input type="submit" name="submit" class="btn-block"/>
<br>
</form>
in PHP script
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "pagesDb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = "SELECT * FROM myPages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$mainPageInfo = $row['mainPageInfo'];
$middlePageInfo = $row['middlePageInfo'];
$containerInfo = $row['containerInfo'];
$content = $row['content'];
$secondContent = $row['secondContent'];
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
$mainPageInfo = $_POST['mainPageInfo'];
$middlePageInfo = $_POST['middlePageInfo'];
$containerInfo = $_POST['containerInfo'];
$content = $_POST['content'];
$secondContent = $_POST['secondContent'];
$sql = "UPDATE myPages SET mainPageInfo='$mainPageInfo',
middlePageInfo='$middlePageInfo',
containerInfo='$containerInfo',
content='$content',
secondContent='$secondContent'
WHERE id=0";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
Second Attempts: It doesn't update my data somehow... please help I tried more than 8 hours with no results :(
if (isset($_POST['submit'])) {
foreach($_POST as $name => $value) {
$sql = "UPDATE myPages SET $name = '$value' WHERE id=1";
}
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
Help would be appreciated, thanks everyone!
Using your Second Attempt as a starting point.
The problem with just using the POST array without being specific is that, in this example you are going to try an update a column on the database called submit i.e. your submit button. Later there may be data on the page that belongs in 2 or more tables.
So create an controlling array containing all the field names from the form that you want to process onto your table.
$db_fields = array('mainPageInfo', 'middlePageInfo', 'containerInfo',
'content', 'secondContent');
$sql = ''; // will hold the query we build dynamically
// was this a user sending data
if ( $_SERVER['REQUEST_METHOD' == 'POST' ) {
foreach($db_fields as $fieldname) {
if ( ! empty($_POST[$fieldname] ) {
$sql .= "$fieldname = '{$_POST[$fieldname]}', ";
}
}
}
$sql = rtrim($sql, ','); // remove the trailing comma
$sql = "UPDATE myPages SET $sql WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

How to show a database colum data on my php script?

I have a php script made by me that can change a database info by taking db name,user,pass and host. Now I want to show a database column info to my php script.
Now how can i do that here is my main db.php script i didn't put the html from script cause i don't think it's necessary.
I have code this but it's showing a error like that
Parse error: syntax error, unexpected T_STRING in /home/abc/public_html/db.php on line 56
Here is my db.php
<style type="text/css">
body {
background-image: url('data:image/gif;base64,R0lGODlhAwADAPcAAAAAAABCAP///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////ywAAAAAAwADAAAICQADABhIcGBAAAA7');
font-family: Tahoma;text-align: center;color: green;
}
img{opacity:0.75; filter:alpha(opacity=75);}
.field_set{
border-color:#4AB825;
}
</style>
<?php
// escape received values
$dbusr = $_POST['usr'];
$dbpsw = $_POST['psw'];
$dbhost = $_POST['host'];
$dbname = $_POST['dbname'];
$admusr = $_POST['admusr'];
$prfx = $_POST['prfx'];
$admpsw = md5($_POST['admpsw']);
// Create connection
$conn = new mysqli($dbhost, $dbusr, $dbpsw);
// Check connection
if ($conn->connect_error) {
die("<br><br><br><br><br><br><br>Database Connection failed: " . $conn->connect_error);
}
echo "<br><br><br><br><br><br><br>Database Connected successfully";
mysqli_select_db($conn,"$dbname");
// use them in query
$sql = "UPDATE ".$prfx."_users SET user_login='".$admusr."',user_pass='".$admpsw."' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "<br><br>Record updated successfully</br></br>Go to your login page <br><br>ex: www.site.com/wp-admin<br><br>and login with your given id and pass";
} else {
echo "<br>Error updating record:" . $conn->error;
}
$sql = "SELECT guid FROM".$prfx."_posts;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Site:" . $row["guid"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
$sql = "SELECT guid FROM".$prfx."_posts;
Should be
$sql = "SELECT guid FROM".$prfx."_posts";
You were missing the closing "
As Dagon said in his comment, In most editors code is shown with color coding, and you can usually see if a " or ' is missing it's closing tag because the color will be off.
UPDATE
Missing space between FROM and $prfx, use below:
$sql = "SELECT guid FROM ".$prfx."_posts";
You are missing a " at the end of line try replace this.
$sql = "SELECT guid FROM".$prfx."_posts";
Whenever you get this error it means that you are missing a closing double quote on that line which is mentioned on the error.
Change this,
$sql = "SELECT guid FROM".$prfx."_posts;
to this,
$sql = "SELECT guid FROM".$prfx."_posts";

PHP : Data which is of one digit is not deleted, but two digit data gets deleted

I have 2 PHP pages to delete employee data from table. For that, user inserts employee id, and press delete, to delete data from table.
Now, problem is, whenever I inserts id of one digit(2,3,8 etc), id is not deleted. However, if two digit id is inserted (12,19,99 etc), it gets deleted.
Please help me to solve where I am wrong.
Here is my code for first PHP page:
<form action="deleteemp.php" method="post" onSubmit="return confirm('Are you sure to delete?')">
Enter id to delete data<input type="text" name="EmpId" required>
<button type="submit" >Delete</button>
</form>
Here is my action PHP page,
<?php
$EmpId = $_POST['EmpId'];
$connection = mysql_connect("localhost", "root", "");
if (!$connection) {
die("Connection failed " . mysql_error());
}
$db_conn = mysql_select_db("hms", $connection);
if (!$db_conn) {
die("Connection failed " . mysql_error());
}
$query = "DELETE FROM employee_details WHERE emp_id = " . $EmpId;
$db_result = mysql_query($query, $connection);
if ($db_result) {
echo "Data Deleted Successfully !";
echo "<br>";
echo "<a href='homepage.php'>Back to homepage</a>";
} else {
echo "Data Not there. Try Again !<br>";
echo "<a href='deleteemp1.php'>Search again</a>";
}
echo "data not here" is incorrect. mysql_query returns boolean false on FAILURE. An empty result (no matching IDs) is NOT a failure. It's a successful query which happens to have an empty result set.
Your code should be more like
$result = mysql_query($query) or die(mysql_error());
if (mysql_affected_rows($result) == 0) {
die("No rows deleted");
}
And note that you are vulnerable to sql injection attacks, and using an obsolete/deprecated DB library.
Try this
$query = "DELETE FROM employee_details WHERE emp_id = '$EmpId'";
$db_result = mysql_query($query, $connection);
if ($db_result)
{
echo "Data Deleted Successfully !";
echo "<br>";
echo "<a href='homepage.php'>Back to homepage</a>";
}
else
{
echo "Data Not there. Try Again !<br>";
echo "<a href='deleteemp1.php'>Search again</a>";
}
This seems some exceptional issue, so try typecasting before passing value to SQL query.
Try using this for assigning value to $EmpId:
$EmpId = (int) $_POST['EmpId'];
can you try to change below code from
$query = "DELETE FROM employee_details WHERE emp_id = " . $EmpId;
TO
$query = "DELETE FROM employee_details WHERE emp_id =".$EmpId;
Just try. This might work for you

Undefined Index - Even with Isset If statement

Can anyone tell me why I am getting an Undefined Index error on my code here.
I have used this setup using the if(isset) condition in other parts of my project after
researching my original Undefined Index errors and ISSET fixed my problems. But it is not working here for some reason and I cannot see why.
This form is POSTING the input:
<form action="addAlbum_Processed.php" method="POST">
<p>Enter artistID of Artist<input type="number" name="artist_id" maxlength="2" size="2"></p>
<p>Enter name of Album to be created<input type="text" name="album_name" size="20"></p>
<input type="submit" name="submit" value="submit"></form>
and this page is processing the form input and updating the albums table in my database:
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}','delete_marker = 0')";
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
mysql_close($connection);
?>
I cannot see where I am going wrong. Regards, TW
This is a tiny example of your problem:
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
You check whether a submit form field was posted before using the other fields. So far, so good. (I would check for the fields that were going to be used, but at least you're checking something.)
But then:
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
You use the fields anyway.
What's more...you don't keep from trying to insert stuff if a form isn't being posted. So any time some rogue spider visits your page, you end up with a blank album in your database.
And that's not even mentioning the fact that you're still using mysql_query.
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
|__________________________| first
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
|_________________________| Repeated
you are fetching variables twice.only one that is if condition is enough.Also use isset for both the variables.
if(isset($_POST['submit']))
{
if isset($_POST['album_name'])
$album_name = $_POST['album_name'];
if isset($_POST['artist_id'])
$artist_id = $_POST['artist_id'];
}
Try something like in addalbam_process.php
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
if(isset($_POST['albam_name']){$album_name = $_POST['album_name']};
if(isset($_POST['artist_id']){$artist_id = $_POST['artist_id']};
}
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}','delete_marker = 0')";
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
mysql_close($connection);
Please, use MYSQLI or PDO to Prevent SQL INJECTION
here </form> is missing
and try something like this
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
A few things.
This line 'delete_marker = 0' should most probably read as
VALUES ('{$artist_id}','{$album_name}','0')
or VALUES ('{$artist_id}','{$album_name}',0)
As I read it 'delete_marker = 0' you are attempting to actually write this value inside the delete_marker column (ArtistID, Album, delete_marker)
Or, you're attempting to use a WHERE delete_marker = 0 clause, which can't be used in an INSERT INTO, but an UPDATE or SELECT rather.
And your if(isset($_POST['submit'])) conditional statement should be wrapping your entire code, instead of just your 2 form variables, because it's basically saying "Ok, assign these 2 variables, then ignore the rest if it's NOT set."
Plus, you're repeating those 2 input variables.
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
(I wrapped your entire code inside the if(isset($_POST['submit'])) conditional statement, btw.
Side note: If you're having a DB connection issue, use this instead:
$connection = mysql_connect('localhost', 'root', '');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
PHP Give this a try:
Sidenote: If this line fails VALUES ('{$artist_id}','{$album_name}', 0) put quotes around the 0 as in '0'
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}', 0)"; // or add quotes around the zero
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
} // closing brace for if(isset($_POST['submit']))
mysql_close($connection);
?>

Categories