I'm trying to create an outgoing link click counter. Found some code online and can't understand for the life of me why it does not update the number within the database. What am I doing wrong here?
<?php
$linkid = $_GET["id"];
mysql_query("UPDATE research SET out = out + 1 WHERE id='$linkid'");
$query = "SELECT * FROM research WHERE id='$linkid'";
$result = mysql_query( $query ) or die ("Error in query: $query. ".mysql_error());
while($row = mysql_fetch_row( $result ) ) {
header ("Location:" .$row[2] );
}
?>
Your best bet to understand how this code is working is to learn to check the data like this:
//connect to db here before the rest of your code
if(isset($_GET["id"]){ //only execute if GET is set
$linkid = $_GET["id"];
echo 'GET = '.$linkid.' <br/>'; //check the value to check against your database for testing
mysql_query("UPDATE research SET out= out+1 WHERE id='$linkid'") or die(mysql_error());
//or die helps detect syntax mistakes
if(mysql_affected_rows()){ //if update did occur
$query = "SELECT fieldname FROM research WHERE id='$linkid'";
//no need to use * just select the on fields you need!
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
if(mysql_num_rows($result)>0){ //if a row is found with that id
$row = mysql_fetch_assoc();
echo 'Field Value = '.$row['fieldname'];
//header("location:".$row['fieldname']); - temporarily commented out as headers already sent
} else { echo 'id does not exist in research table'; }
} else { echo 'update did not occur'; }
} else { echo 'GET not set!'; }
I see nothing wrong with your syntax but a few checkers can help explain why it might not be working!
With my script check the outputs and compare it to your database (be sure to check fieldname to the actual name of the field!
It should highlight why it's not working. I've added comments to explain what is going on encase your unfamiliar with some of the function names that i used.
Related
<?php
include('core/init.php');//database connection
if(isset($_POST['btn_submit'])){
$sqlQuery = mysql_query("UPDATE `position` SET `ATR`='".mysql_real_escape_string($_POST['ATR'])."',
$resultQuery = mysql_query($connection, $sqlQuery) or die (mysql_error($connection));
if(mysql_affected_rows($resultQuery) > 0){
echo "updated";
}else{
echo "failed";
}
header('Location:position2.php');
$result = mysql_query("SELECT * FROM position WHERE ID='" .$_POST["id"]. "'");
$row2 = mysql_fetch_array($result);
}
?>
//What this code does it it updates the database based on user input and I am trying to loop through each of the user input as update and display but it doesn't seem to work
($_POST['ATR'])."',
Is missing a closing "
Also formatting code makes it easier to read and debug.
Ive been trying to display a "bid" from the database to no success.
here is my error
Fatal error: Function name must be a string in /home/rslistc1/public_html/get-bids.php on line 7
here is my code
<?php
include('session.php');
?>
<?php
require_once('mysql_connect.php');
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
$result3 = mysql_query($query3) OR die($mysql_error());
$num = mysql_num_rows($result3);
while ($row = mysql_fetch_array($result3, MYSQL_ASSOC)) { ?>
<?php echo''.$row['bid'].'';
}
?>
Any idea
Before we address the line 7 issue, lets check other errors. In order to request a query to a MYSQL database, we need to create a connection:
$con = mysqli_connect("ip_address","user","password","database_name");
Once we have that connection, let us check if we can actually connect to the database:
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
Appreciate that mysqli_error() function uses the connection. Now the query string:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
You are sending a query to look for a username called "$login_session" and it would most likely not find any match. To add strings from variables will be as follow:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '" . $login_session . "'";
Now, for the error in line 7
result3 = mysql_query($con, $query3) OR die($mysql_error($con));
As you can see, both mysql function use the connection to check for errors. Try it and let me know if everything works fine.
Edit:
Terribly sorry my friend, I just forgot to put a little letter "i" on the line, also, I would like to show you my way to deal with the query result. First, the line as it should be:
$result3 = mysqli_query($con, $query3);
Notice the i after mysql. Now let us check whether we got some rows or not:
if (!$result3) {
die('Could not retrieve data: ' . mysqli_error($con));
} else {
while ($row = mysqli_fetch_array($result3)) {
//Show your results
}
}
I have a database table with six records which are urls for six different shiny servers. There is a program that populates, on a real time basis, whether each of the servers are available. I have written a query that returns the url of the first available server. I have tested the script and determined the selection process works. I now want to perform a redirect to the available server using the "header" function and I am having difficulty determining the correct syntax. The URLs are in the format of "muscle.mysite.com:3535nameScan." Here is what I have at present.
$q = "SELECT url FROM ShinyServers WHERE Availability = '1' LIMIT 0, 1 ";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
//printf ("%s\n", $row["url"]);
$url= printf ("%s\n", $row["url"]);
header ("Location: $url"); //redirect to muscle*
mysqli_close($dbc);
exit(); //before or after mysqli_close? I think after.
When I execute, I see mysite.com/40 in the address bar and I get a 404.
I tried this:
header ("Location: $row"); //redirect to muscle*
When I execute, I get "mysite.com/array in the address bar and I get my 404 page. I have tried many variations and I have thoroughly confused myself.
I hope you can see what I am trying to do. I have backed up to what does work which is
$q = "SELECT url FROM ShinyServers WHERE Availability = '1' LIMIT 0, 1 ";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
printf ("%s\n", $row["url"]);
mysqli_close($dbc);
I get the first url that is available and I can see the results printed as muscle.mysite.com:3535nameScan. Now, I need to capture the results as a variable I can use in an UPDATE query and the header function. I have been searching for an answer and I have not found one as yet. I thought a different fetch command would be the answer but I could not find one that would apply to what I want to do.
I believe I am heading in the correct direction my using the suggestion to use "sprintf." However, I am still not able to "update" the table. Here is where I am at now.
error_reporting(E_ALL);
$q = "SELECT url FROM ShinyServers WHERE Availability = '1' LIMIT 0, 1 "; //make query
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
//printf ("%s\n", $row["url"]);
$url= sprintf ("%s\n", $row["url"]); //assign results to a variable?
echo "$url";
$qu = "UPDATE ShinyServers SET Availability = 0 WHERE url = $url LIMIT 1";
$ru = mysqli_query($dbc, $qu);
if (mysqli_affected_rows ($dbc) ==1){
echo '<p> The status has been updated</p>';
}else{
echo '<p class="error"> The status could not be updated</p>';
}
I get the expected results from 'echo "$url";' But I am getting the error message "The status could not be updated." I have been at this for so long I am afraid I am overlooking something. Is there a problem with the code or could there be a problem with the DB table? I looked at the DB table, created by someone else, and I noticed it does not have a unique column.
With prodigitalson and Dan08's help, I have a script that works. It is as follows
error_reporting(E_ALL);
$q = "SELECT url FROM ShinyServers WHERE Availability = '1' LIMIT 0, 1 "; //make query
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
//printf ("%s\n", $row["url"]);
$url= sprintf ("%s", $row["url"]); //assign results to a variable
//echo "$url";
$qu = "UPDATE ShinyServers SET Availability = 0 WHERE url = '$url' LIMIT 1";
$ru = mysqli_query($dbc, $qu);
if (mysqli_affected_rows ($dbc) ==1){
echo ' The status has been updated';
}else{
echo ' The status could not be updated';
}
mysqli_close($dbc);
header ("Location: http://$url");
exit();
My DB table is updated and I am redirected (I know I do not need the conditional statement). I learned also that the "header" function had to be after mysqli_close. I found that in the php manual. A little more tweaking and then I have the task of marrying this script into a registration script and a login script. Whoppee...thanks again.
This is my final script and it works perfectly
<?php
//selecting available server and update status
include_once '../DB/test1DB.php'; //connect to DB
error_reporting(E_ALL);
$q = "SELECT url FROM ShinyServers WHERE Availability = '0' LIMIT 0, 1 "; //make query
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$url = sprintf("%s", $row["url"]); //assign results to a variable
$qu = "UPDATE ShinyServers SET Availability = 1 WHERE url = '$url' LIMIT 1";
mysqli_close($dbc);
header("Location: http://$url");
exit();
I need to print data from users table for username that is logged in, for example, need to bring HP, attack, defence, gold... I found many answers here and after this I am sure I am gone ask more questions. Please help...
<?php
session_start()
if(isset($_SESSION['username'])){
echo "Welcome {$_SESSION['username']}";
}
require_once 'config.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die('Error connecting to mysql');
mysql_select_db($dbname);
$query = sprintf("SELECT ID FROM users WHERE UPPER(username) = UPPER('%s')",
mysql_real_escape_string($_SESSION['username']));
$result = mysql_query($query);
list($userID) = mysql_fetch_row($result);
echo "Health Points:".$row['HP'];
echo "Attack:";
echo "Defence:";
echo "Gold:";
?>
You have to query for all the information you actually want. So your query should look like this:
SELECT HP,Atk,Def,Gold FROM ...
This will retrieve the named fields from your database and not just the ID.
Also, you never assign your row, it should read
$row = mysql_fetch_row($result);
(But see my comment below).
1 - there is missing ; in the first line
2 - try "SELECT * " instead of "SELECT ID"
3 - $row is not defined , try :
$row = mysql_fetch_assoc($result);
instead of
list($userID) = mysql_fetch_row($result);
check the manual for the difference between mysql_fetch_row and mysql_fetch_assoc
mysql_fetch_assoc
I have run across a problem during my query service to add a row in an online database in PHP. The addition of the row works just fine. I get user id and book id from the url and fetch the names of the book and the user to put into the row which i add to my third and last table.
When I get the names, put them in an array, json encode it and then echo it, it works. But when I put them in the row it prints resource id#3 and resource id#4 instead of the names.
Any ideas?
Here is my service:
<?php
$con = mysql_connect("localhost","root","root");
$userid=$_GET['uid'];
$id = $_GET['bookid'];
$type = $_GET['type'];
$zero = '0';
$one = '1';
$date = date("Y-m-d");
$arr = array();
if (!$con)
{
die('Could not connect: ' . mysql_error());
echo "error connection";
}
mysql_select_db("Jineel_lib",$con) or die("Could not select database");
$bkName = mysql_query("SELECT Name from books where ID='".$id."'");
$userName = mysql_query("SELECT Name from people WHERE User_ID='".$userid."'");
while($obj = mysql_fetch_object($userName))
{
$arr[] = $obj;
}
echo json_encode($arr);
if($type == 'borrow')
{
$query="UPDATE books set Availablity = '".$zero."' where ID= '".$id."' ";
mysql_query($query) or die (" borrow operation failed due to query 1");
$query1="INSERT into borrowed (BookID, BookName, BorrowerID, BorrowedName, DateBorrowed, Extended, Returned) values('".$id."','".$bkName."','".$userid."','".$userName."','".$date."','".$zero."','".$zero."')";
mysql_query($query1) or die (" borrow operation failed to due query 2");
echo "borrow success";
}
else if($type=='return')
{
$query="UPDATE books set Availablity = '".$one."' where ID= '".$id."' ";
mysql_query($query) or die (" return operation failed");
$query1="UPDATE borrowed set Returned = '".$one."' where BookID= '".$id."' ";
mysql_query($query1) or die (" return operation failed 1");
echo "return success";
}
else
echo "invalid parameters";
?>
THANK YOU IN ADVANCE
You don't actually retrieve the userName value here:
$userName = mysql_query("SELECT Name...
$userName is just the result resource object returned from the query. You do use mysql_fetch_object later on, which is appropriate, but then you try to use the actual result resource in your insert query:
$query1="INSERT into borrowed ...
It gets converted to the string you see. Instead, you need to use $obj->Name (you fetch the result into $obj, and presumably there is only one result). If there is more than one possible result, you will have to do that in a loop.
Listen to all of the comments on your question.