simple outbound link tracker - Why isn't this working? - php

<?php
/** Connect to DB */
mysql_connect("localhost", "dbuser", "pass") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());
$link_id = $_GET['link_id'];
/** increase the counter of the URL*/
mysql_query("UPDATE link_count SET count = count + 1 WHERE ID = $link_id") or die(mysql_error());
/** retrieve URL */
$result = mysql_query("SELECT * FROM link_count WHERE ID = $link_id") or die(mysql_error());
$row = mysql_fetch_array($result);
header( "Location:" .$row['URL'] );
?>
Of course db info has been changed for posting here. Where I try to use
count.php?link_id=1
in a link I get "Unknown column 'ID' in 'where clause'"
I checked to make sure there were all single quotes instead of backticks....
EDIT: Solution provided by #Kai Qing in a comment to CanSpice's answer.

I would suggest making sure your column is actually called ID and not id. It's telling you the column doesn't exist and that may be because it actually doesn't exist as typed. Also, count is a reserved mysql term. change it to this:
mysql_query("UPDATE link_count SET `count` = `count` + 1 WHERE ID = $link_id") or die(mysql_error());
and before you get lectured on injection holes, wrap your $link_id like so:
mysql_real_escape_string($link_id)

Your column is probably named id, not ID. Column names are case-sensitive.

$sql = sprintf("UPDATE link_count SET count = count + 1 WHERE ID = %s",mysql_real_escape_string($_GET['link_id']));
mysql_query($sql) or die(mysql_error());
Also you might not want to print all of your mysql_errors out once this is in production.

Related

colname returns first entry in database table, not the one selected

I have a page that when the user clicks on a horse to see more info on that horse (referred by ID number in mysql table), it only returns the first record, NOT the one you chose.
The page is http://www.cbarlranch.com/?pg=forsale
<?php require_once('dbaseinfo.php'); ?>
<?php
//set variables
$colname_rsStallion = "1";
if (isset($HTTP_GET_VARS['ID'])) {
$colname_rsStallion = (get_magic_quotes_gpc()) ? $HTTP_GET_VARS['ID'] : addslashes($HTTP_GET_VARS['ID']);}
//select database
mysql_select_db($db, $conn);
//build the query
$query_rsStallion =
sprintf("SELECT * FROM table WHERE ID = '%s'", $colname_rsStallion);
//set more variables
$rsStallion = mysql_query($query_rsStallion, $conn) or die(mysql_error());
$row_rsStallion = mysql_fetch_assoc($rsStallion);
$totalRows_rsStallion = mysql_num_rows($rsStallion);
?>
Please help. Thanks!
Try using $_GET['ID'] rather than $HTTP_GET_VARS. If your IF fails the it will default to the record with ID = 1 (which is likely your first record)

Update table based on condition (While Loop)

So I am trying to update my table based on a singe parameter:
The dateEntered field must be blank.
And I want to randomly select 50 rows, and update the blank ownerID fields to "Tester"
Here is what I have:
<?php
include("includes/constants.php");
include("includes/opendb.php");
$query = "SELECT * FROM contacts WHERE dateEntered='' ORDER BY RAND() LIMIT 50";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$firstid = $row['id'];
$query2 = mysql_query("UPDATE contacts
SET ownerID = 'Tester'
WHERE id = '$firstid'");
$result2 = mysql_query($query2) or die(mysql_error());
}
?>
It will update a single record, then quit and give me:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
The first part that selects the records works fine, its query2 that won't update all 50 records, just one. Maybe I am writing this wrong.
mysql_query needs only one time
$query2 = mysql_query("UPDATE contacts
SET ownerID = 'Tester'
WHERE id = '$firstid'");
$result2 = mysql_query($query2) or die(mysql_error());
to
$result2 = mysql_query("UPDATE contacts
SET ownerID = 'Tester'
WHERE id = '$firstid'");
These answers are spot on, so I will only add some additional information, and a suggestion. When you are querying mysql the first time, $query1 is being set to the result resource, which for
$query1 = mysql_query("UPDATE contacts SET ownerID = 'Tester' WHERE id = '$firstid'");
returns a result of 1 (Boolean TRUE), which is why your second query failed, cause "1" isn't a valid mysql query string. As Greg P stated, you can fix your current script by eliminating the secondary mysql query.
However, you could improve the script entirely, and make fewer sql calls, by using this.
<?php
include("includes/constants.php");
include("includes/opendb.php");
$query = "UPDATE contacts SET owenerID='Tester' WHERE dateEntered='' ORDER BY RAND() LIMIT 50";
$result = mysql_query($query) or die(mysql_error());

Using Update Query to Copy Column Data

I need to copy the value in a column named TEAM from one row into another row. Both rows need to have the same team name. This is my query that doesn't work:
$query = "UPDATE profiles SET team = (SELECT team FROM profiles WHERE id = '$coach_id') WHERE id = '$player_id'";
I have tried removing single quotes, removing "FROM profiles", changing value to table.value, tried to give a newdata.clan alias, and I have even tried changing the values to integers instead of parameters. Nothing works, and this is what I get:
Error: You have an error in your SQL
syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near 'WHERE id = '') WHERE id = ''' at
line 3
$query1 = "SELECT team FROM profiles WHERE id = '$coach_id'";
/* get the value of the first query and assign it to a variable like $team_name */
$query2 = "UPDATE profiles SET team = '$team_name' WHERE id = '$player_id'";
Also, you should surround your PHP variables in curly braces:
$query = "UPDATE profiles SET team = \"(SELECT team FROM profiles WHERE id = '{$coach_id}')\" WHERE id = '{$player_id}'";
From the MySQL manual:
"Currently, you cannot update a table
and select from the same table in a
subquery."
Source: http://dev.mysql.com/doc/refman/5.0/en/update.html
Use the method that FinalForm wrote:
<?
$coach_id = 2;
$player_id = 1;
$query1 = "SELECT team FROM profiles WHERE id = '$coach_id'";
$rs = mysql_query($query1);
if ($row = mysql_fetch_array($rs)) {
$team_name = $row['team'];
$query2 = "UPDATE profiles SET team = '$team_name' WHERE id = '$player_id'";
mysql_query($query2);
// Done, updated if there is an id = 1
} else {
// No id with id = 2
}
?>

Updating with multiple variables with MySQL + PHP

I have 2 variables that contain a a string of text. I need to update them in the table, but out of the 20 + different variations of about 5 different scripts that I've tried out, it just doesn't update!
I can update using this:
mysql_query("UPDATE cart SET quantity = $q WHERE sessionid='" .session_id(). "' AND description = '$d'") or die(mysql_error());
but I am now working on a different page, where I need a slightly different update query. Which is:
UPDATE cart SET quantity = $q WHERE sessionid = $somethin AND description = $desc
And for that I have:
mysql_query("UPDATE cart SET quantity = $q WHERE sessionid = $o AND description = $d") or die(mysql_error());
(I have tried many variations with different quotes in different places for the above query, but nothing works!)
I have also tried:
$conn = mysql_connect("my01..com", "dbase", "2354ret345ert");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'UPDATE cart
SET quantity="'.$q.'"
WHERE sessionid="$o" AND description = "$d"';
mysql_select_db('mysql_94569_dbase');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
That last one doesn't display any errors, in fact, it even tells me that it has successfully updated! But it's lying. It hasn't updated anything.
Can someone please help me out here, I am really getting sick of reading tutorial after turorial and never learning anything because they all have differnt syntax and none of it seems to work.
What I would like to do is:
UPDATE table SET columnname = $this WHERE thiscolumn = $this AND thiscolumn = $that
$this = $var
Thank you
You are missing the quotes in description and SessionID, do it like this:
mysql_query("UPDATE cart
SET quantity = '".$q."'
WHERE sessionid = '".$o."' AND description = '".$d."'");
In order to save you confusion, I would recommend start using concatenation operator (eg 'UPDATE '.$table .' SET ...')instead of writing variables directly to strings (eg. "UPDATE $table SET ...").
in this case your query would look like:
mysql_query("UPDATE cart SET quantity = ".$q." WHERE sessionid='" .session_id(). "' AND description = '".$d."'") or die(mysql_error());
This might help you to find problems with quotes and parenthesis quicker
BAD:
I had this query in php:
$query = "UPDATE users SET username = ".$nume." WHERE id = ".$userID;
That did this SQL:
UPDATE users SET username = elev WHERE id = 2
GOOD: For it to work I changed it to this php:
$query = "UPDATE users SET username = ".'"'.$nume.'"'." WHERE id = ".$userID;
That did this SQL:
UPDATE users SET username = "elev" WHERE id = 2

Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)

Categories