PHP / SQL Query dynamic record from url - php

I currently have this:
<?php
$con = mysql_connect('localhost', 'root', 'dev');
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB");
$query = "SELECT * FROM pages where id=1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$contents = $row['content'];
echo $contents;
?>
See this part: SELECT * FROM pages where id=1
1 is the record id and it's currently hardcoded. What I need to do is change it so it get's the record id from the url...for example: mysite.com/index.php?2 would show record id 2 ...
How do I go about doing this?

Turn that hardcoded value into a variable.
<?php
//assumes you have a querystring like: http://mysite.com/index.php?id=3
$id = $_GET['id'];
$con = mysql_connect('localhost', 'root', 'dev');
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB");
//Make your variable safe for use with mysql
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM pages where id=" . $id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$contents = $row['content'];
echo $contents;
?>

let say the url is something like that: mysite.com/index.php?id=2
in your index.php:
<?php
$id = $_GET['id'];
// your sanitizing methods for id to avoid SQL injection
$con = mysql_connect('localhost', 'root', 'dev');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("diy");
$query = "SELECT * FROM pages where id = ".$id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$contents = $row['content'];
echo $contents;
?>
Beware of SQL injection

Basic example using mysite.com/index.php?id=x as your URLs where x is the Id:
$id = (int)$_GET['id'];
$query = sprintf("
SELECT *
FROM pages
WHERE id = %d",
mysql_real_escape_string($id)
);
With your connection lines included of course, you should also validate.

URL data is interpreted using the GET method. First, you should look here for how to use it, and here for how to read it.
Basically, your URL will look like this:
mysite.com/index.php?id=2
Then, you could read in the URL variable like this:
$id = mysql_real_escape_string($_GET['id']);
mysql_real_escape_string() will help avoid SQL injection, but requires an existing connection, so your code would look like this:
<?php
// Set up connection
$id = mysql_real_escape_string($_GET['id']);
$query = 'SELECT * FROM pages where id = '.$id;
// Run the query
?>

You could use a regular expression to extract it from the URL.
$retval=preg_match( "#(\d+)$#", $_SERVER['REQUEST_URI'], $match );
$index=-1;
if( $retval ) {
$index = $match[1];
}
This approach allows you to continue using the URL scheme you described in the question without prepending id=. Whether that's a good idea or not is probably debateable.

http://pastebin.com/NEZe7jjL
<?php
$dbh = new PDO('mysql:host=127.0.0.1;dbname=test', 'user', 'password', array(
PDO::ATTR_EMULATE_PREPARES => true,
PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8',
));
$stmt = $dbh->prepare('SELECT * FROM `pages` WHERE `id` = :page');
$stmt->bindValue(':page', $_GET['page'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
?>
yoursite.com/index.php?page=2

Related

get SPECIFIC database row with php

Ok so now I have this code where I'm retrieving data from db table:
<?php
$link = mysql_connect('funki.fresh-tech.it', 'userns3e', '2w3rwrtwd');
$db = mysql_select_db("funkireport", $link);
$query = mysql_query("select * from machine", $link);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$row = mysql_fetch_row($query);
var_dump($row);
echo 'Connected successfully';
mysql_close($link);
?>
So in this table I have many rows and each has a "serial_number" column.... now what I'm trying to do is, get the row with the SPECIFIC serial_number (which I have as a variable)...
so for example
# serial_number
1 AB1
2 AB2
3 AB3
4 AB4
5 AB5
and for example I have a variable $product = AB2
How can I GET from the database only the row that has "serial_number" = $product=AB2 ?
Please can somebody help me with this. Thank you
Use MySQL WHERE Clauses like that :-
$query = mysql_query("select * from machine where serial_number = '$product'", $link);
Your Query work like that :-
select * from machine where serial_number = 'AB2'
Well it is actually not hard you just need to know what to do here. So as Rahautos said, you can use the WHERE clause.
Your code(fixed):
<?php
$link = mysql_connect('funki.fresh-tech.it', 'userns3e', '2w3rwrtwd');
$db = mysql_select_db("funkireport", $link);
$query = mysql_query("select * from machine where serial_key='SERIAL KEY'", $link);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$row = mysql_fetch_array($query);
echo $row['serial_key'];
mysql_close($link);
?>
or instead you can use a form, input the key in the text field and get the results out with automation:
<?php
if(isset($_POST['submit']) {
$link = mysqli_connect('funki.fresh-tech.it', 'userns3e', '2w3rwrtwd');
$db = mysqli_select_db("funkireport", $link);
$key = $_POST['key']
$query = mysql_query("select * from machine where serial_key='$key'", $link);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$row = mysql_fetch_array($query);
echo $row['serial_key'];
mysql_close($link);
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>Key:</label>
<input type="text" name="key">
<input type="submit" name="submit">
</form>

I can't connect to db or pull data

I am using this same code `
php $postId = 41;
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname="my_db";
$host="localhost";
$user="guessthe";
$dbh=mysql_connect ($host,$user,"correctPassword?") or die ('I cannot connect to the database because: ' . mysql_error(). '');
mysql_select_db ("$dbname") or die('I cannot select the database because: ' . mysql_error());
$sql="SELECT * FROM games WHERE postId = $postId";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
There is a value in the gameLength row! I can't get this code to pull any of the rows! Any idea what i'm doing wrong?
You're using MySQL, which is depcirated - and will be phased out. You should use MySQLi or PDO instead. Also, your $postId is defined outside a PHP-tag? Might just be a copy/paste mistake? Anyway, you can try the code below, which is in MySQLi:
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname = "my_db";
$host = "localhost";
$user = "guessthe";
// Connecting to the database
$mysqli = new mysqli($host, $user, "correctPassword?", $dbname);
if ($mysqli->connect_errno) {
// If we are here, the connection failed
echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$sql ="SELECT * FROM games WHERE postId = $postId";
if ($result = $mysqli->query($sql)) {
// If the query was sucsessfull, we can get the rows
while ($row = $result->fetch_assoc()) {
$gameId = $row['id'];
$game100s = $row['game100s'];
$gamesPlayedAllTime = $row['gamesPlayed'];
$gamesPointsAllTime = $row['gameScore'];
$gameLength = $row['gameLength']; // get number of questions
$gameScore = $row['gameScore'];
$gameType = $row['gameType'];
$gametitle = $row['gameSubTitle'];
}
} else {
// If the query failed, do something here
}
echo $gameLength;
?>
I see some people commenting that you need to put the $postId variable inside quotes in the query, but when using double-quotes (") variables will be posted, so it's not really needed. Also note that things are case-sensitive, so if your results doesn't show, check for spelling-mistakes.
There are many errors in your code
Try this...
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength">
<?php
// MySQL connect configuration
$host = "localhost";
$dbname = "my_db";
$user = "username";
$password = "password";
$dbh = mysql_connect ($host,$user,$password) or die ('I cannot connect to the database because: ' . mysql_error() . '');
mysql_select_db($dbname, $dbh) or die('I cannot select the database because: ' . mysql_error());
$sql = "SELECT * FROM games WHERE postId='$postId'";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)){
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
}
?>
You need to fix this is your code and that should fix the error.
$sql="SELECT * FROM games WHERE postId ='".$postId."' ";
If you want all the records you can use a while loop. Here is some pseudo code.
while($row = mysql_fect_assoc($query)){
echo $row["THE THING YOU WANT"];
...
}

SQL UPDATE broken

I have been troubleshooting this code for awhile, but it won't work and I can't find out why. Does anyone see an error? Also, I'm aware that there is no WHERE statement, I intentionally want to update all records.
<?php
// Connect to database
$link = mysqli_connect('*****', '*****', '*****');
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
mysqli_select_db(bullseye);
// Varaible setting
$header = $_POST['header'];
$video = $_POST['video'];
$m_title = $_POST['m_title'];
$m_sub = $_POST['m_sub'];
$w_title = $_POST['w_title'];
$w_sub = $_POST['w_sub'];
$w_t1 = $_POST['w_t1'];
$w_t2 = $_POST['w_t2'];
$w_t3 = $_POST['w_t3'];
$w_d1 = $_POST['w_d1'];
$w_d2 = $_POST['w_d2'];
$w_d3 = $_POST['w_d3'];
$p_title = $_POST['p_title'];
$p_sub = $_POST['p_sub'];
mysqli_query($link, "UPDATE tbl_name SET
header=$header,
video=$video,
mtitle=$m_title,
msub=$m_sub,
wtitle=$w_title,
wsub=$w_sub,
wt1=$w_t1,
wt2=$w_t2,
wt3=$w_t3,
wd1=$w_d1
wd2=$w_d2,
wd3=$w_d3,
ptitle=$p_title,
psub=$p_sub");
?>
EDIT:
mysqli_query($link, "UPDATE about SET
header='$header',
video='$video',
mtitle='$m_title',
msub='$m_sub',
wtitle='$w_title',
wsub='$w_sub',
wt1='$w_t1',
wt2='$w_t2',
wt3='$w_t3',
wd1='$w_d1',
wd2='$w_d2',
wd3='$w_d3',
ptitle='$p_title',
psub='$p_sub'");
First off, you should prepare it using MySQLi as to protect yourself from MySQL injection:
$mysqli = new mysqli("localhost", "my_user", "my_password", "bullseye");
$query = $mysqli->prepare("UPDATE tbl_name SET
header=?,
video=?,
mtitle=?,
msub=?,
wtitle=?,
wsub=?,
wt1=?,
wt2=?,
wt3=?,
wd1=?
wd2=?,
wd3=?,
ptitle=?,
psub=?");
$query->bind_param("ssssssssssssss, $header, $video, $m_title, $m_sub, $w_title, $w_t1, $w_t2, $w_t3, $w_d1, $w_d2, $w_d3, $p_title, $p_sub");
$query->execute();
$query->close();
$mysqli->close();
This code should work. If it doesn't please post the error.
It looks you need to concat your query with your variables. And not just a big string.
You should use the following to chose your database:
mysqli_select_db($link, "bullseye");

How can I use PHP to delete all records in a MySQL database?

I would like to scrap all my records in a database. I want to use just a PHP script, not PhpMyAdmin. I have will be using a MySQL database administrator account. What SQL query should I use?
You could run a query:
/* Assumes the existence of a few key variables
and further, that your user has the appropriate permissions */
mysql_connect( $host, $user, $pass ) or die( mysql_error() );
mysql_select_db( $db ) or die( mysql_error() );
mysql_query( "TRUNCATE TABLE tablename" );
Or
mysql_query( "DELETE FROM tablename" );
CAUTION!
These queries will result in all records being deleted. If you want only certain records to be dropped, add a where clause:
mysql_query( "DELETE FROM tablename WHERE userid = 5" );
To completely empty the database, dropping all tables (if that's what you really want to do), run this PHP script.
<?php
header('Content-Type: text/plain');
$link = mysqli_connect('host', 'username', 'password');
mysqli_select_db($link, 'database_name');
mysqli_set_charset($link, 'utf8');
$sql = 'SHOW TABLE STATUS FROM `database_name`;';
$result = mysqli_query($link, $sql);
$rows = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
$n = 0;
foreach ($rows as $row) {
$sql = 'DROP TABLE IF EXISTS `' . mysql_real_escape_string($row['Name']) . '`;';
mysqli_query($link, $sql);
++$n;
}
echo $n . 'tables dropped' . PHP_EOL;
exit(__FILE__ . ': ' . __LINE__);

Return sql query as array

I'm using jqueryui and its Autocomplete plugin. It use a json to extract items.
I want to modify it so that items will be extracted from my db.
Here is how items should be :
$items = array(
"Great <em>Bittern</em>"=>"Botaurus stellaris",
"Great2 <em>Bittern</em>"=>"Botaurus stellaris 2"
);
How to make an sql query that extract data from a table and write it like the code above into the php file ?
Table : customer
id_customer | name_customer | country_customer
I want that array produce id_customer => name_customer
The query is just:
SELECT id_customer, name_customer FROM customer
and you can generate the array like so (assuming you are using MySQL):
$items = array();
$result = mysql_query($sql);
while(($row = mysql_fetch_assoc($result))) {
$items[$row['id_customer']] = $row['name_customer'];
}
References: MySQL SELECT syntax, mysql_query(), mysql_fetch_assoc()
<?php
//Use mysql_connect for connect to a Db
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select a DB
$db_selected = mysql_select_db('db_name', $link);
if (!$db_selected) {
die ('Can\'t use dbame_n : ' . mysql_error());
}
//Build a query
$sql = "SELECT id_customer, name_customer FROM customer";
//Send de query to db
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// Initialize Array
$arr_customers = array();
while(($row = mysql_fetch_assoc($result))) {
$arr_customers[$row['id_customer']] = $row['name_customer'];
}
// convert to JSON
$json = json_encode($arr_customers);
// Send to JqueryUI
echo $json;
exit();
?>

Categories