I recently converted a code block into a function so I can call it easily more than just once. My problem is that as soon as I related the block to a function it fails the SQL query every time. Here's my code block:
function checkEvent()
{
if(!empty($_GET['e']))
{
$sql = mysqli_query($link, "SELECT * FROM events WHERE EventID = '" . mysqli_real_escape_string($link, $_GET['e']) . "'");
if($sql && mysqli_num_rows($sql)==1)
{
if($row = mysqli_fetch_row($sql))
{
$eventid = $row[0];
$eventname = $row[1];
$desc = $row[2];
$time = $row[3];
echo $_GET['e'];
}
}
else
{
echo $sql;
$failure = "Num Rows Error encountered: " . mysqli_error($link) . " / Num Rows: " . mysqli_num_rows($sqlE);
}
}
}
Now, I've added echos in the relevant places to check and where it currently says echo $sql; if I change that to echo "Fail."; then it will indeed do that. I have tried to get the result as a number of rows and that comes back blank. I don't understand this as my EventID is an AUTO INCREMENT and as such HAD to start at 1. I've triple checked the first entry is 1 as well.
I'm probably not seeing something really obvious, I just can't understand why this code block stopped working the instant I placed a function block around it.
$link doesn't exist inside your function. You either need to pass that as a parameter to the function or skip it entirely and use the "current" DB connection.
"current" in quotes because while it should work just fine while you're utilising a single database connection for the entire process, as soon as you'd start using multiple connections (to connect to multiple databases,) this approach would fail terribly.
Related
I am trying to use the INSERT INTO SQL statement in php. It will input everything correctly up until the last value ($bands_bio). Instead of putting in the correct information, it leaves the value blank. I have looked over everything and can't seem to find any sort of syntax errors.
$page_title = "Create a new band";
require ('includes/database.php');
require_once 'includes/bandsHeader.php';
$band_name = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_name', FILTER_SANITIZE_STRING)));
$band_photo = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_photo', FILTER_SANITIZE_STRING)));
$genre = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'genre', FILTER_SANITIZE_STRING)));
$band_bio = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_bio', FILTER_SANITIZE_STRING)));
echo $band_bio;
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = "")) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/searchFooter.php';
exit;
}
$albums = 0;
$sql = "INSERT INTO bands VALUES (NULL, '$band_name', '$genre', '$albums', '$band_bio')";
$query = #$conn->query($sql);
if (!$query) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/footer.php';
exit;
}
As you can see, I echoed out $band_bio in order to see if it was getting the right value from my form that uses the GET method, which it is so that's not the issue. It has no problem inserting everything correctly up until the last value, which is supposed to be the last column called band_bio in my bands table in my database. It will not output any errors or anything, either. It's almost as if it's taking the string data from the variable and removing all of the text before it inserts the information.
I have been working on this website for a few weeks now and have used the INSERT INTO statement the exact same way on other pages and it works just fine. This is the first thing that has really stumped me and I can't figure it out. Any help is appreciated.
When inserting, ensure that your pk (id) field is set to auto-increment.
This way, you can exert more control over your queries. You should be more successful with:
$sql = "INSERT INTO bands "
. "(`band_name`,`genre`,`numof_albums`,`band_bio`) "
. "VALUES ('$band_name', '$genre', '$albums', '$band_bio')";
By not specifying the pk field, INNODB will automatically increment and insert it for you.
The idea is that you want to specify which columns are being inserted into. Relying on column ordering by mysql is fine, but there may be something at play in your case.
There should be no reason why band_bio would be "left off". You would get a column-mismatch error.
Totally found the answer myself! It, in fact, was a syntax error.
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = ""))
The variable $band_bio was being assigned to a blank string in the if statement since I accidentally used an assignment operator rather than a comparison operator. So the correct code would need to be $band_bio === "" rather than $band_bio = "".
I swear, the problem is always something so much simpler than you think it's going to be.
I created an background working script, that updates my database table on a condition.
Here is my main script:
<?php
require_once('conn.php');
$query = "SELECT * FROM user WHERE id = '" . $_COOKIE['username'] . "'";
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($data);
if($row['ehp'] > $row['required_ehp']) {
// The 'ehp' column is greater than 'required_php'
$calc = $row['ehp'] % $row['required_ehp'];
$new = $row['required_ehp'] * 12;
$new_lvl = $row['level'] + 1;
$query2 = "UPDATE user set level = '$new_lvl', ehp = '$calc', required_ehp = '$new'";
mysqli_query($dbc, $query2);
echo 'query successful';
} else {
echo 'query unsuccessful' . mysql_error();
}
echo $row['ehp'] % $row['required_ehp'];
echo $row['required_ehp'];
?>
The error message I am getting from this script is:
query unsuccessful
Warning: Division by zero in H:\AppServ\www\sp\userlevel.php on line 21
I don't know what's is wrong. Please help me.
Here is the database column's image.
Since you see query unsuccessful, that means that the line if($row['ehp'] > $row['required_ehp']) is false.
In the line echo 'query unsuccessful' . mysql_error(); there is no mysql error, therefore you only see the line query unsuccessful.
Also you get the devision by 0 warning. This is caused by the line echo $row['ehp'] % $row['required_ehp'];. It seems $row['required_ehp'] is 0.
Summing this all up, perhaps the data you expect to be in $row is not what you are expecting. Maybe the cookie data is incorrect?
Also, putting the cookie data straight into the query is a horrible idea, and easily to hack.
Okay I found out my mistake it was just that in id in my database, I was searching for the username column. Sorry to bother you all.
hi i am developing a website and i need to delete files from a server i currently have the following code
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include($_SERVER['DOCUMENT_ROOT'] . "/Scripts/Functions.php");
top();
THis Seems To Be The Problem
$query = "SELECT * FROM 'Gallery' WHERE 'ID' = '20'";
if (!mysqli_query(connect(),$query))
{
die('Error: ' . mysqli_error(connect()));
}
else
{
$Result = mysqli_query(connect(),$query);
while ($row = mysqli_fetch_assoc($Result))
{
$file = get_local($row['Image_Location']);
unlink($file);
$query2 = "DELETE FROM Gallery WHERE ID='20'";
if (mysqli_query(connect(),$query2))
{
header("Location: http://test.co.uk/Gallery/Edit/")
}
else
{
die('Error: ' . mysqli_error(connect()));
}
}
}
bottom();
?>
after going through the code i have worked out that it is an error with the if (!mysqli_query(connect(),$query)) section yet i i cant manage to work out whats wrong.
You appear to be missing a semi-colon on this line:
header("Location: http://www.littlesaintspreschool.co.uk/Gallery/Edit/")
The first problem I spot is that you have your table surrounded by single quotes.
When referring to database elements, like,
the database name
the table name
the field name
You must use backticks ` which is located to the left of the 1 key and above tab.
The second problem I see is that you are passing a function to mysqli_query. Not knowing what the return value is for connect()... I can't exactly say that that is the problem. Regardless, you should store your connection in a variable rather than a function.
I get a list of records and each record is a question / answer / timestamp.
I created a basic PHP report:
<?php
$con = mysql_connect("localhost", "login", "pass");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query(" SELECT *
FROM `experiment`
where userid = 73");
while ($row = mysql_fetch_array($result)) {
echo "question " . $row['question'] . "answer " . $row['answer'] .
"time " . $row['time'] . "stamp " . $row['createdAt'] . "<br>";
}
I need some way to compare the row in front of createdAt and the row after createdAt.
If the difference between two rows is bigger then 2 minutes, the thing should echo "warning".
I'll assume a couple of things on your behalf. This may change the value of the answer, but you simply haven't provided the necessary information for an answer to be feasible at this point.
I am going to assume that you are looping through the data records. You imply this by stating that there is a display of multiple rows. Your SQL query only gets the data of one row. I'll assume that you actually have gotten an entire record set instead. Because otherwise, the data structure needs to be examined for its design choices. I am also making an assumption on how userid is used in a table, mind, so that's my personal bias.
As record sets are collected, they can be manipulated. You're using the ancient mysql_* method here. I recommend that you read the PDO methodology that php has available at 5.2.7+ and consider upgrading your php version if you don't already have it.
The manipulation can take many forms.
$previousRecord = 0;
foreach ($recordSet as $index=>$record){
$recordSet[$index]['warningTime'] = FALSE;
if ($previousRecord){
if (($record['createdAt']-$previousRecord) > 120){
$recordSet[$index]['warningTime'] = TRUE;
}
}
$previousRecord = $record['createdAt'];
// Other data manipulation logic for page presentation
}
This should inject the warning right into the dataset that can be displayed whenever you want it to be. I do prefer a seperation of functions for maintainability; calling the database, extracting/formatting the data, displaying the data. It makes future changes much easier, also allows for code portability. You do not have this in your code, which means that whenever you do something like this again, well, you'll re-invent the wheel.
$createdAt = null;
while($row = mysql_fetch_array($result)) :
// initialise on first run
if ($createdAt === null) :
$createdAt = $row['createdAt'];
endif;
// now $createdAt is the value of the last row... if so, echo warning, else echo nothing
echo checkCreatedIsOlderThanTwoMinutes($createdAt, $row['createdAt']) === true ? "WARNING!" : "";
echo "question ". $row['question']. "answer ". $row['answer']. "time ".$row['time']."stamp ". $row['createdAt']."<br>";
endwhile;
I don't have a clue what the format of your createdAt looks like, so I use this pseudo-function:
function checkCreatedIsOlderThanTwoMinutes($oldCreatedAt, $newCreatedAd)
{
// check that stuff
}
Hope that helps.
Hey guys, Im doing a series of if statements based on a session variable that is set (which looks at a value in the DB and then decides whether to empty the session, or name it. However I'm having problems in that the session is always named, regardless of whether the record in the database is '0' or not. The query works fine when run in mysql. Here's the code:
session_start();
$_SESSION['MemberType'] = '';
mysql_select_db($database_choices, $choices);
$query = "Select lifemember from registrants where username = '" . $_SESSION[kt_login_user] . "'";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
while($row = mysql_fetch_array($result))
{
if ($row['lifemember'] == '1')
{
$_SESSION['MemberType'] = 'LifeMember';
}
else if($row['lifemember'] == '0')
{
$_SESSION['MemberType'] = '';
}
}
Precheck: If you are getting any 'Headers already sent...' then you have some output already on the page which is preventing the setting of session.
Otherwise try debugging steps like:
1) Do an echo $row['lifemember'] inside the while loop so that you know REAL value of what's been fetched from DB.
2) In else block, change it to $_SESSION['MemberType'] = 'Hello'; Then see, whether Hello is printed or not?