Selecting row from DB using mysql/php - php

I'm trying to get a row from the DB using php, i've made an html form that's supposed to take a book title from users and gets the review from the DB about this book, and then post it in an input text, the form's action leads to the following function :
function GetReview($BookTitle)
{
require'DB.php';
if(empty($_POST['BookTitle']))
{
echo " You must enter a book name!";
return false;
}
$BookTitle = mysql_real_escape_string($BookTitle);
$q="Select Reviews from Users_Booklist where (Book_Title like '%" .$BookTitle."%');";
if(!mysql_query($q,$con))
{
die("Error".mysql_error());
}
else
{
$row = mysql_fetch_row($q);
?>
<html>
<head><title>Delete Review </title>
</head>
<body>
<br>
<form name="DeleteReview " action="DeleteReviewsFunction.php" method="post">
Review: <input type="text" name="Review" size="200" value="<?php echo $row[0]; ?>"/>
<input type="submit" value="Delete Review" />
</form>
</body>
</html>
<?php
}
}
GetReview($_POST['BookTitle'])
However, it leads me to the next form with nothing in the input text and this warning:
Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\GetReview.php on line 20
I've searched and tried different code but still same result.
Could anyone please tell me where the error is???... Thanks

$qq = mysql_query($q,$con);
if(!$qq) {
// (...)
$row = mysql_fetch_row($qq);

I'm not going to be a lot of help, but your question seems to be where the error is occuring, and I can tell you that.
It's in the $row = mysql_fetch_row($q); line.
You can tell this because the error record starts with mysql_fetch_row(), and the above line is the only mention of mysql_fetch_row() in the code.

Check the SQL query by printing the output of $q variable with:
echo $q;
Now, try to execute it from your MySQL client. Collect the results (if there are) and check for errors.
A suggestion: If you want, you can use a tool like ezSQL that can be very useful (especially for code organization)

Related

PHP and MYSQLI Check if user ID is present and if not create it

I have been looking for 3 weeks on the Internet for an answer to this question and cannot find anything that even comes close or in handy. I have a Database Table that i need to have checked. If a Users_ID is present in that table, I would like my code to display an update.php link in my form action="" tag and if the Users_ID is not present in that db table, then i would like to have an Insertdb.php page to be linked in the form instead of an update.php page. Here is what I have:
PHP Code:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
while($display = $results->fetch_array(MYSQLI_ASSOC)) {
$uid = $display['uid'];
if($display['uid']==""){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
And my HTML section looks like this:
HTML Code:
<form action="<?php echo $pagelink; ?>" method="POST">
<input type="text" value="" placeholder="Insert Value" name="something" />
<input type="submit" value="Submit Data" name="submit_data_to_db" />
</form>
How would I go about doing this? My current method Posted above is what I'm currently using, however its displaying only <form action="" method="POST"> when i check it against the pages view-source. Please help me anyway you can. Any and all help would be greatly appreciated. Thank you
you usually use num_rows method:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
if($results->num_rows() > 0){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
I see you use $con but I see nowhere you have declared it.
Can you confirm that actually exists? It is possible your script is halting its execution at that point.
Also a few things I would implement in there:
1. When you use variables that come from external sources (like your forms), or even other variables really, always care for SQL injection;
2. Your if & else can be reduced to just an if (when you find an ID). To all others case, you wish a default behaviour that is your else. So something like this:
$pageLink = "insertintodb.php";
if (!empty($display['uid'])) {
$pageLink = "updatedb.php"
}

Run two completely different sqli queries inside one script

I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.

GET POST mysql data on next page

Ok, I haven't done much of this sort of stuff, so I am clueless right now.
On the first page you hit the form submit that generates a bunch of information/stuff and displays it underneath submit button, but I don't know how to take the displayed information and use it on the next page I will show some of my code. btw I know the code is bad, just ignore that fact.
<form name="input" action="slaymonster.php" method="post" id="id">
<div align="center">
<input name="Submit" id="Submit" type="submit" class="button" value="Explore Map!"/>
</div>
</form>
if (isset($_POST['Submit'])) {
include 'includes/mapstuff.php';
// So here we pick a random row from the table pokemon notice the order by rand
$sql23 = "SELECT * FROM map1pokemon ORDER BY RAND() LIMIT 1;";
// We then check for errors
$result23 = mysql_query($sql23) or die(mysql_error());
// we then make the result into a virable called battle_get23
$battle_get23 = mysql_fetch_array($result23);
$sql2 = "SELECT * FROM pokemon WHERE name='".$battle_get23['pokemon']."'";
$result2 = mysql_query($sql2) or die(mysql_error());
$battle_get2 = mysql_fetch_array($result2);
// Now we need to make sure the image is safe be for we use it
$pic2= mysql_real_escape_string($battle_get2['pic']);
$pic = strip_tags($pic2);
include 'includes/maptypes.php';
?>
<form name="inputt" action="" method="post">
<div align="center">
<input type="submit" class="catch" value="Catch Pokemon" name="catch">
</div>
</form>
<p></p>
<?php
echo "You have just found a " ;
echo $randomview97[0];
echo " ";
echo $battle_get23['pokemon'];
$_SESSION['pokemon'] = $battle_get23['pokemon'];
$_SESSION['type'] = $randomview97[0];
$_SESSION['pic'] = $battle_get2;
$_SESSION['money'] = $randomview2[0];
$_SESSION['level'] = $randomview3[0];
$_SESSION['ticket'] = $randomview4;
?>
<p></p>
<?php
echo "You have gained ".$randomview3[0]." levels" ;
echo " ";
?>
<p></p>
<?php
echo "You have received $".$randomview2[0]."" ;
echo " ";
?>
<p></p>
<?php
echo "</center>";
}
?>
it displays the pokemon's picture it's name, type,amount of money you got ect...
I need all that information to be useable on the next page.
Any help is appreciated :)
At the top of your PHP code, be sure to include session_start();
You are already using session variables, so you should refer here to see what a PHP session is: PHP session_start() - Manual. It makes sure to do exactly what you are asking for (someone may point out that in certain cases session_start(); is not necessary, but for your purposes, while learning, stick to the Manual for best practices)
This information will be usable on the next 'page', just as the manual describes, and will be available, until you call something like session_destroy().
If you want to pass the information from one page to another. You have to put the result inside the form tag. Then it is possible to pass the information to another page. Or you can put it on the session and get information from any page.
you got my point? If you explain what you want to do. Then I will do something for you.

php & mysql query - cannot return the variable I need from MySQL

update: There must be a minor syntax error in some accompanying validation for $_GET variable. I rewrote everything carefully and the script now works. Thank you all!
I've spent more than 5 hours trying to find what's wrong with my code.
1st page: a db query retrieves some vimeo videos from the db and presents each one of them with an "edit" link which dynamically gets the video's id (vimeo 8-digit id). To do this, I just call the following function:
function edit_portfolio_videos() {
global $connection;
$query = "SELECT * FROM portfolio_videos ORDER BY video_id ASC";
$portfolio_videos_set = mysql_query($query, $connection);
confirm_query($portfolio_videos_set);
while ($portfolio_video = mysql_fetch_array($portfolio_videos_set)) {
echo "<iframe src=\"http://player.vimeo.com/video/";
echo $portfolio_video['video_code'];
echo "?title=0&byline=0&portrait=0&color=ffffff\" width=\"400\" height=\"230\" frameborder=\"0\" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe><br />";
echo "Edit this Video";
}
}
2nd page: This is the page where each video will be edited by the administrator. Example URL would be something like "http://www.my_website.com/edit_portfolio_video.php?videocode=34956540". On this page, I use the following function to get the array from the previous page's script:
function get_selected_video_by_id($video_code) {
global $connection;
$query = "SELECT * FROM portfolio_videos ";
$query .= "WHERE video_code = '$video_code' ";
$query .= "LIMIT 1";
$videos_set = mysql_query($query, $connection);
confirm_query($videos_set);
if ($video = mysql_fetch_array($videos_set)) {
return $video;
} else { $video = NULL; }
}
and then...
$selected_video = get_selected_video_by_id($_GET['videocode']);
in order to put every kind of data related to the selected video in the edit form:
<form action="edit_portfolio_video.php?videoid=<?php echo $selected_video['video_code']; ?>" method="post">
<input type="text" name="video_title" value="<?php echo $selected_video['video_title']; ?>" />
</p>
<p>Video Code (vimeo):<br />
<input type="text" name="video_code" value="<?php echo $selected_video['video_code']; ?>" />
</p>
<p>Video Description:<br/>
<textarea name="video_description" rows="5" cols="70"><?php echo $selected_video['video_description']; ?></textarea>
</p>
<p>
<input type="submit" name="submit" value="Save Video" />
</p>
</form>
But the form's fields don't get populated, as there seems to be a problem with the $video variable I'm trying to get (returned from get_selected_video_by_id function). The video code is stored as "INT" (length: 11) in the database and is printed as string in the 2nd page's URL. I've tried to write the function's query in many ways but I can't get it to work.
I'd appreciate some help on this, thank you all.
Note: The confirm_query function does this simple job:
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed: " . mysql_error());
}
}
I think you should try this instead for your get_selected_video_by_id SQL query.
$query = "SELECT * FROM portfolio_videos WHERE video_code = ".$video_code;
Of course watch out for SQL injection in your parameters, and also, as someone already suggested please consider using PDO or MySQLi.
Your Form seems strange:
you are using a POST mode to pass a GET value (edit_portfolio_video.php?videoid=...etc...).
But this shouldn't be the problem.
In this line:
$selected_video = get_selected_video_by_id($_GET['videocode']);
are you sure the GET parameter you are passing is videocode? Or is it videoid?

$_POST not working in PHP

<html>
<head><title>HEllo</title></head>
<body>
<input type="text" name="id">
<input type="text" name="name">
<input type="text" name="address">
<input type ="submit" name = "s" value = "Employee">
<?php
$link =mysql_connect('localhost','root') or die("Failed");
mysql_select_db("gagan",$link) or die("database not exists");
if($_POST['s']=="Employee")
{
print "g";
$id = mysql_real_escape_string($_POST['id']);
$name = $_POST['name'];
$address = $_POST['address'];
print "hi";
$update = "update emp set name = $name, address=$address where id = $id";
$result = mysql_query($update,$link);
print "Hello";
if($result)
{
print "Updated";
}
else{
print "$update";
}
}
?>
</body>
</html>
When i run this code it produce an notice and the above code is not working.
Notice: Undefined index: s in C:\wamp\www\1.php on line 12
What's the problem in my code can anybody tell me?
You forgot the form tag.
<form action="yourform.php" method="POST">
You need to ensure that array member is set first. Try using the result of isset($_POST['s']) to ensure it is set before trying to access it.
You need the form tage with the method set to post.
ie
The main problem (in addition to the missing form tag) is that the program flow continues to the part that tries to save the data even when the form hasn't been submitted yet. You must check that the form has been submitted before trying to save the data, or even easier would be if you moved the data saving part to its own script.
You also have an invalid SQL query but that's another matter :)

Categories