Help with PHP and MYSQL select function - php

I am creating a browser statistics script in PHP.
When PHP finds a match in a table how do I retrieve the row and pull all three fields of the table into separate variables.
My table rows are (browser, version, amount)
so I want to select everything from the TB were
browser = $browser and version = $version.
But when this happens how do I add one to the amount field and resubmit the row. Without altering anything else. Below is the code I have.
$browser_name= "MSIE";
$version = "7";
$query = ("SELECT * FROM $TB
WERE browser = '$browser_name' AND version = '$version'");
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count == 1)
{
$mysql = ("SELECT * FROM $TB
WERE browser = '$browser_name' AND version = '$version'");
//code to add 1 to amount would be here
}
else
{
//if browser is not detected insert fresh row.
$mysql = "INSERT INTO $TB (browser, version, amount)
VALUES ('$browser_name', '$version', 1)";
}
I have been looking around for answers for ages but they just tell me how to select information out of a DB as a whole.

update table set amount_field = amount_field + 1 where browser = '$browser_name' and version = '$version'
I don't understand why you make twice the same select.

$browser_name= "MSIE";
$version = "7";
$query = "SELECT * FROM $TB WHERE browser = '$browser_name' AND version = '$version'";
$result = mysql_query($query);
if($data = mysql_fetch_assoc($result))
{
print_r($data);
//use UPDATE from other answers if you need one here.
}
else
{
//if browser is not detected insert fresh row.
mysql_query("INSERT INTO $TB (browser, version, amount)
VALUES ('$browser_name', '$version', 1)");
}
Beware of SQL injections!

SELECT * FROM $TB WHERE browser
you have a mistake it must be WHERE instead of WERE.

You update query will be like this
UPDATE $TB SET ammount = 1 WHERE browser = $browser and version = $version

There are hundreds of issues with your query like sanitization etc. I suggest you read a good mySQL book to improve the queries. But to answer your question:
//code to add 1 to ammount would be here
mysql_query("update $TB set amount = amount + 1 where browser = '".mysql_real_escape_string($browser_name)."' and version = '".mysql_real_escape_string($version)."'");

First of all, you should connect to db using
$db = new mysqli('host','user','pass','dbname');
Then, your query isn't right. You have a sql syntax error.
SELECT * FROM table WHERE column = value
So, without prepare, your code should look like:
$tb = 'table_name'; // to avoid sql injections use addslashes() to your input
$browserName = addslashes('browser_name'); // like this
$version = '7';
$db = new mysqli('host','user','pass','dbname');
$result = $db->query("SELECT * FROM $tb WERE browser = '$browserName' AND version = '$version'");
// Than, you can fetch it.
while ($result->fetch as $row) {
echo $row['yourColumn']; // will display value of your row.
}
$db->query("INSERT INTO $tb (browser, version) VALUES ('$browser_name', '$version')";
}");
And, that's all. You can count your records using mysql count() method. Your code will work. I advice you, at first go to php.net and check the doc. There are many examples.

Related

Whats wrong in my php mysql counter script code?

I am writing a Php 5 and Mysql 5 page counter script. When a student having id as 'visitorid' visits a page having id 'pageid' (both int(11)) the page counter tries to log the visit in 'visitors' database. But counter is not updating in mysql db, instead the visit_counter int(4) turns to 0.Whats wrong with my code? visitdate is datetime.
<?php
$pageid = 101;
$visitorid = 234;
$sql = "SELECT * FROM visitors
WHERE pageid = ".$pageid."
AND visitorid = ".$visitorid;
$temp = mysql_query($sql) or die("Error 1.<br>".mysql_error());
$data = mysql_fetch_array($temp);
// visit_counter is a field in table
if(($data['visit_counter']) != NULL){
echo "Entery exists <br>";
// Tried below version also
$visit = " SET visit_counter = visit_counter+1";
//$visit_counter = $data['visit_counter'];
//$visit = " SET visit_counter = ".$visit_counter++ ;
// Valid SQL
// UPDATE `visitors`
// SET visit_counter = visit_counter+1
// WHERE pageid = 101 and visitorid=234
// This manual sql query updates in phpmyadmin
$sql = "UPDATE visitors ".$visit."
AND visitdate = NOW()
WHERE pageid = ".$pageid."
AND visitorid = ".$visitorid;
$temp = mysql_query($sql) or die("ERROR 3.<br>".mysql_error());
//No error is displayed on above query.
} else {
//first entry
$visit_count = "1";
$sql = "INSERT INTO visitors
(`pageid`,`visitorid`, `visitdate`, `visit_counter`)
VALUES ('".$pageid."','".$visitorid."', NOW(), '".$visit_count."')";
$temp = mysql_query($sql);
//first entry is inserted successfully
//and visit_counter shows 1 as entry.
}
?>
Can anyone tell me whats wrong with this code?
Oh! I got answer by myself. Sometimes just little errors make us go crazy..
I made a mistake in udate query.. rather than using and I should have user a comma instead. .. working well now!

MySQL - Batch rename all rows in PHP

So in this piece of code, I just deleted a row from the table, and so, the values for img_pos were:
1,2,3,4,5
And now, they are (assuming we deleted the third entry):
1,2,4,5
Of course, I want this to be:
1,2,3,4
So I have to batch rename the rows.
I got this, but doesn't seem to work....
$sql = "SELECT * FROM $tableImg WHERE img_acc = $accid ORDER BY img_pos";
$res = mysql_query($sql);
$num = mysql_num_rows($res);
$i = 0;
$n = 1;
while($i<$num){
$sql = "SELECT * FROM $tableImg WHERE img_acc = $accid ORDER BY img_pos DESC LIMIT $i,1";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$img_pos = $row['img_pos'];
$sql = "UPDATE $tableImg SET img_pos = '$n' WHERE img_acc = '$accid' AND img_pos = '$img_pos'";
$res = mysql_query($sql);
$i++;
$n++;
}
mysql_close();
$tableImg is just a variable containing the table name, that works just fine.
I guessthe problem is somewhere around "$img_pos = $row['img_pos'];", because all the querys are used somewhere differently, be it slightly different, and they should work...
Thanks in advance!
I ended up simply doing this:
$i = 1;
while($row = mysql_fetch_array($res)){
$old_pos = $row['img_pos'];
$sql = "UPDATE $tableImg SET img_pos = $i WHERE img_acc = $accid AND img_pos = $old_pos";
$res = mysql_query($sql);
$i++;
};
This is quite possible, just totally unnecessary. The nice thing about digital data is that you don't have to look at it so it doesn't matter if it's a bit gappy, does it?
If you REALLY want to do this (say, you are building an application and you are just cleaning up the stuff you deleted whilst working on it) the following example will do in in SQL, as this simple example shows:
CREATE TABLE disorder (id int,stuff CHAR(6));
CREATE TABLE disorder2 (id SERIAL,stuff CHAR(6));
INSERT INTO disorder (id,stuff)
VALUES
('1','ONE'),
('2','TWO'),
('3','THREE'),
('4','FOUR'),
('5','FIVE');
DELETE FROM disorder WHERE id='3';
INSERT INTO disorder2 (stuff) SELECT stuff FROM disorder;
TRUNCATE TABLE disorder;
INSERT INTO disorder SELECT * from disorder2;
DROP TABLE disorder2;
This can be seen in action on sqlfiddle but it's pretty obvious. If you do a SELECT * from disorder, you will see why you probably shouldn't do this sort of thing.
Your tables really do need to have primary keys. This speeds searches/indexing and makes them useful. Look up database normal forms for a thorough discussion of the reasoning.

Database not updating row

Before you assume I didn't establish a database connection, I did. the only portion of the code that does not update is the if empty statements.
All the values can be echoed out correctly, it's just that query doesn't work.
This is in directory config and named stuff.php
$user = $mysqli->real_escape_string($_SESSION['username']);
$user_query = "SELECT * FROM users WHERE username = '$user'";
$result = $mysqli->query($user_query);
$row = $result->fetch_assoc();
$referrer = $row['ref'];
$refearn = $row['refearn'];
verify.php
include('config/stuff.php');
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Get Real IP
$IP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$IP = $_SERVER['REMOTE_ADDR'];
}
if ($IP=="external server ip here") {
if (!empty($referrer)){
$mysqli->query("UPDATE users SET points=points+10, refearn = refearn+10 WHERE username='".$referrer."'") or die(mysqli_error($mysqli));
}
$mysqli->query("UPDATE users SET points=points+".$earnings.", completed = completed+1 WHERE username='".$subid."'") or die(mysqli_error($mysqli));
}
My guess is you could try to retrieve the value of points through a query then add to it so you're just updating to a simple value. However, if mysql_error() is returning an error, it should be easier to figure out.
Example:
$getPoints = mysql_query("SELECT points FROM table WHERE condition");
$points = mysql_result($getPoints, 0, "points");
$update = mysql_query("UPDATE table SET points=" . ($points+10) . " WHERE condition");
Hope that helps. Another consideration, though. Why use an endif structure unless you're breaking PHP tags to display content?
try this:
$mysqli->query("UPDATE `users` SET `points`=`points`+10, `refearn` = `refearn`+10 WHERE `username`='".$referrer."'") or die(mysqli_error($mysqli));
Hope this helps. What I think is, mysql query might be taking those as constant - not as the mysql rows. Try that

MySQL not working when ODBC is in the same script

A company I am working for has a Progress DB that store much of their information. They asked me to make a PHP script that can pull data from it and merge it with data inside of a MySQL database.
At first I figured I would just fetch the data, but after a while I found that the Progress DB was incredibly slow. I decided to have the page fetch from either MySQL or Progress depending on which had it (MySQL trumping Progress)
I ran into a problem though in that for some reason ODBC and MySQL don't seem to be able to function when both open. How can I solve this? Is it possible to do what I am needing it to do?
Note: I threw catches for errors all over the place and MySQL never returned an error. The ODBC always goes and returns the content, but it never INSERTs it into the MySQL DB
Here is my code:
$job_num = "59505";
$fields = 'JobNum, Name, City, State, StartDate, ReqDueDate';
$field_queries = 'j.JobNum AS JobNum, Name, City, State, jh.StartDate AS StartDate, ReqDueDate';
//Determine if there is a record in the MySQL DB that has the job
$mysqlr = mysql_query("SELECT * FROM jobsinfo WHERE JobNum='$job_num'");
if(!$mysqlr){
die(mysql_error());
}
//If there is a record, display it from there: faster
if(mysql_num_rows($mysqlr) > 0){
//Take the fields and explode them into an array so that it can be looped through.
$field_array = explode(', ', $fields);
//Return each row from the database
while($row = mysql_fetch_array($mysqlr)){
//Return all fields in the array
foreach($field_array as $key=>$field){
echo $field .": ".$row[$field]."<br>";
}
//Because the Description comes from a different part of the Progress include it here.
echo "Description:<br>".$row['Description'];
}
}else{
//If there is no record in the MySQL display it from the Progress AND copy it over.
//Begin by inserting a record to later be modified
mysql_query("INSERT INTO jobsinfo (JobNum) VALUES ('$job_num')") or die(mysql_error());
$id = mysql_insert_id();
//Connect to the Progress DB
$conodbc = odbc_connect($dsn, $username, $password, SQL_CUR_USE_ODBC);
//Explode the fields so that they can be looped through.
$field_array = explode(', ', $fields);
//Make the query to the Progress DB. Merge many tables into one query using JOINs
$sql = "SELECT TOP 1 ".$field_queries." FROM PUB.JobProd j LEFT JOIN PUB.BookOrd b ON j.OrderNum=b.OrderNum LEFT JOIN PUB.Customer c ON b.CustNum=c.CustNum LEFT JOIN PUB.JobHead jh ON j.JobNum=jh.JobNum WHERE j.JobNum = '$job_num' ORDER BY ReqDueDate DESC";
//Execute the query
$rs = odbc_exec($conodbc,$sql) or die('Select failed!');
//For each record loop through
while(odbc_fetch_row($rs)){
//For each field display
foreach($field_array as $key=>$field){
$value = odbc_result($rs, $field);
echo $field.": ".$value."<br>";
//Update the previously inserted row with the correct information
mysql_query("UPDATE jobsinfo SET ".$field."='$value' WHERE id = '$id'");
}
}
//Because there are multiple job parts it is easiest to just loop through it seperately and not JOIN it
$sql_asmbl = "SELECT * FROM PUB.JobAsmbl AS ja WHERE JobNum = '$job_num'";
//Execture
$rs_asmbl = odbc_exec($conodbc,$sql_asmbl) or die('Select failed!');
echo 'Description:<br>';
$ptdesc ='';
//Loop through all the rows that match the job number
while(odbc_fetch_row($rs_asmbl)){
$ptdesc .= odbc_result($rs_asmbl, 'PartNum') ." - ";
$ptdesc .= odbc_result($rs_asmbl, 'Description') ."<br>";
}
$ptdesc = mysql_real_escape_string($ptdesc);
//Update the MySQL
mysql_query("UPDATE jobsinfo SET Description = '$ptdesc' WHERE id = '$id'");
//Display it
echo $ptdesc;
//Close DB's
odbc_close($conodbc);
mysql_close($conn);
}
You are assuming that MySQL queries always run successfully:
$mysql = mysql_query("SELECT * FROM jobsinfo WHERE JobNum='$job_num'");
if(mysql_num_rows($mysql) > 0){
}
You should always test it explicitly:
$mysql = mysql_query("SELECT * FROM jobsinfo WHERE JobNum='$job_num'")
if( !$mysql ){
die(mysql_error());
}
I see that you make an ODBC connection, but I do not see mysql_connect() or something similar using mysqli or PDO. Are you actually opening a socket connection to mysql and you just left that out of this code example or did you forget to make the connection in your code?
I moved the INSERT up a bit and removed the ' from ('JobNum') and now it works fine.
Found the cause of the error. Both the MySQL and ODBC were using $conn as their connecting variable. This was causing errors.

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