I'm a beginner in php and mysql, I just want to know how can I put values that I got from a select query into variables.
For example I used this mysql query :
$req="SELECT type, titre, auteur, abstract, keywords FROM manusrit WHERE file='$name';";
$req1=mysql_query($req);
I want to put the value of the column type in $type variable and the value of auteur in a variable called $auteur and the same for abstract, and keywords.
How can I do this?
FIRST of all use PDO instead of mysqli.
Example :
$link = mysql_pconnect($hostname, $username, $password) or die('Could not connect');
//echo 'Connected successfully';
mysql_select_db($dbname, $link);
$name = $_POST['Name'];
$query ="SELECT type, titre, auteur, abstract, keywords FROM manusrit WHERE file='$name';";
mysql_query("SET NAMES 'utf8'", $link);
$result = mysql_query($query, $link);
//Now You FETCH result and read one by one
while ($row = mysql_fetch_assoc($result)) {
//Access COLMN like this
print $row['abstract'];
print $row['keywords'];
}
Related
I am trying to update for some products their category in database. I want to find products that have in their name a specific word and after that I want to update the category for this products.
I want to select IDs from sho_posts where sho_posts.post_title contain this part of word '%Audio CD%' and after that to update the sho_term_relationships.term_taxonomy_id with value 2 where sho_term_relationships.object_id=sho_posts.id.
I wrote a little PHP code but it make only selection part. What is wrong?
<?php
$username = "user_name";
$password = "password";
$hostname = "host";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("1812233_shoping",$dbhandle)
or die("Could not select examples");
echo "Connected to MySQL<br>";
$result = mysql_query ("SELECT `id` FROM `sho_posts` WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%' ");
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}."<br>";
}
$sql = "UPDATE 'sho_term_relationships'
SET 'term_taxonomy_id' = '123'
WHERE 'object_id' = $row";
//close the connection
mysql_close($dbhandle);
My new cod for script now is:
$username = "_shoping";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("_shoping",$dbhandle)
or die("Could not select examples");
echo "Connected to MySQL<br>";
$result = mysql_query ("SELECT `id` FROM `sho_posts` WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%' ");
while ($row = mysql_fetch_array($result)) {
$id[] = $row['id'];
/*echo "ID2:".$id."<br>";*/
}
foreach ($id as $value) {
echo "value:".$value."<br>";
}
/*$id = $row['id'];*/
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = '123'
WHERE object_id =".$value;
mysql_query($sql);
//close the connection
mysql_close($dbhandle);
now it make an update but only for one row, how to make for all rows? From select query I get 4 result
Try this:
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = '123'
WHERE object_id = ".$row{'id'};
And make sure to run the query mysql_query($sql)
Also, I think you might want to add this query inside the while loop
You are using single quotes instead of backticks (which are in this case not necessary). Change your update query to this:
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = 123
WHERE object_id = $row";
Also, you are missing some pieces of your code; nothing will be called on that query. It's not being executed at all.
Also you have some other problems here, mainly due to the high risk of sql injection. First of all stop using mysql_ functions, they are deprecated. You should prepare your variables. Here's a demonstration of the key parts of your script in mysqli_ format.
This should also solve most of your issues (there may be a few more if I don't full understand your original question).
You would call your database like this (and check for errors)
$dbhandle = new mysqli($hostname, $username, $password);
if ($dhandle->connect_error) {
die("Connection failed: " . $dbhandle->connect_error);
}
Then you would select your data like this (assuming that term might not be the same every time, and might be coming from a post variable named search).
Edit: For example, if you have an HTML form that is getting this variable like so:
<input type="select" name="search_term" />
you name the variable like this:
$search = $_POST['search_term'];
and then you set it up for your query for the like operator
$search_term = '%'.$search.'%';
$result = $dbhandle->prepare("SELECT `id`
FROM `sho_posts`
WHERE CONVERT(`post_title` USING utf8)
LIKE ? ");
$result->bind_param("s",$search_term);
$result->execute();
$result->bind_result($id);
And then you can get your data through the while loop like so
while ($result->fetch()) {
... stuff you want to do here...
}
$result->close();
Then you would use this in your update query (which would take a similar syntax), and you can just get the information from $id which was created with the bind_result above:
$sql = $dbhandle->("UPDATE sho_term_relationships
SET term_taxonomy_id = 123
WHERE object_id = ?");
$sql->bind_param("s",$id);
$sql->execute();
$sql->close();
It may take a little bit to get used to this, but I find it easier to parse, and also is much more secure
I'm trying to retrieve multiple data from a database with a PHP function, but somehow when I do this multiple times it gives a MySQL connection error.
$heat=getStat("heat", $userid);
$cash=getStat("cash", $userid);
echo mysql_error();
I use the code above to assign variables by calling a function which retrieves the stats from a database.
When I use the above codes separately, they work. But when I put them together they fail.
Is this a simple you-are-a-beginner-noob-programming-mistake?
I forgot to post the function so here it is:
function getStat($statName,$userID) {
require_once 'config.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die('Error connecting to MySQL' . mysql_error());
mysql_select_db($dbname);
$query = sprintf("SELECT value FROM user_stats WHERE stat_id = (SELECT id FROM stats WHERE display_name = '%s' OR short_name = '%s') AND user_id = '%s'",
mysql_real_escape_string($statName),
mysql_real_escape_string($statName),
mysql_real_escape_string($userID));
$result = mysql_query($query);
list($value) = mysql_fetch_row($result);
return $value;
}
The problem is most likely caused by the require_once. As this is where you are pulling in your config for the database connection. The second time the require is executed it will not pull in the code required to define your database connection vars.
As #MichaelBerkowski has stated, it would be much better to have one global connection when the script loads, and make use of this connection for each request to the database. However if you wish to stick with the way you have currently, this should solve the problem:
function getStat($statName,$userID) {
require 'config.php'; /// <-- note this has changed to just require
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die ('Error connecting to mysql');
mysql_select_db($dbname);
$query = sprintf("SELECT value FROM user_stats WHERE stat_id = (SELECT id FROM stats WHERE display_name = '%s' OR short_name = '%s') AND user_id = '%s'",
mysql_real_escape_string($statName),
mysql_real_escape_string($statName),
mysql_real_escape_string($userID));
$result = mysql_query($query);
list($value) = mysql_fetch_row($result);
return $value;
}
BIt of a php/mysql noob here, hope someone can help.
Ok so i have a URL which has an id in the querystring like so: wwww.mysite.com/page1.php?id=1
What i want to do is connect to a table in the database and get the data from the columns on one row where the first column named ID equals the id number held in the querystring.
I then want to print the data from each column in different div's elsewhere on the page.
There's also the additional issue of what to do if there's no row in the table with the same id as the querystring, i'd want it to change the id in the querystring to 1 and load that rows data.
I had a little go, i know it connects ok but i have no idea if the rest is what i want:
<?php
$link = mysql_connect('Address', 'Database', 'Password');
if (!$link) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = "select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per=".$_GET['ID']."";
echo $result['A'];
mysql_close($link);
?>
And then put this in the div's to print the data.
<?php echo $result['A']; ?>
Am i along the right lines or completely wrong?
$dbConnection = mysql_connect('Address', 'Database', 'Password');
if (!$dbConnection) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = $dbConnection->prepare("select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per = ?");
$query->bind_param('s', $per);
$query->execute();
$result = $query->get_result();
<?php echo $result; ?>
use this code first to avoid SQL Injection second that's the way it should work in PHP first prepare the query second execute and only then show it.
Use mysql_query function in your code.
mysql_* functions is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.
<?php
$link = mysql_connect('Address', 'Database', 'Password');
if (!$link) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = "select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per=$per";
$result = mysql_query($query, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['A'];
mysql_close($link);
?>
I have a simple insert statement that should use $GLOBALS that has my connection string in. Problem is that it does not insert the data. Have I done this correctly?
Insert.php
<?php
require 'core/init.php';
$Name = $_REQUEST["Name"];
$Venue = $_REQUEST["Venue"];
$Category = $_REQUEST["Category"];
$query = "INSERT INTO bands (Name, Venue, Category)
VALUES ('$Name', '$Venue', '$Category')";
mysql_query ($query,$GLOBALS)
or die ("could not add to database");
echo("You have added: <br />");
$result = mysql_query("SELECT * FROM bands ORDER BY Band_id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
echo $row['Name']. "" . $row['Venue']. "" . $row['Category'];
echo "<br />";
}
?>
You need to connect mysql with mysql_connect() function then select database with mysql_select_db() function then you can call mysql_query function
you just cant execute queries with query string parameter you need to execute that connection query first and then select your database
And i suggest you to use mysqli instead of mysql cuz mysql methods will be deprecated soon
You don't put whole $GLOBALS variable in your mysql_query() call. You put the specific variable with the connection string only:
mysql_query($query, $GLOBALS['connection']) // Assuming you called the connection var "connection"
or die ("could not add to database");
I am new for PHP5 OOP concept.
Please give some example source code for "How to insert data using oops concept?".I want to use pure php5 concept for this even in the connection.php page also.
I want to improve my knowledge. please any one help me....
I know below the basic concept
insert_db.php
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
connectio.php
<?php
// connect database code
$dbhost ='localhost';
$dbuser = 'tomking';
$dbpass = 'dsfds';
$dbname = 'mydb';
//connectivity of database
$conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error Connecting to mysql');
mysql_select_db($dbname);
?>
Use Mysqli or PDO for using sql queries instead of directly pass variables to query.
This will cause sql injection when you directly pass variable to query
If you want to pass variable to sql query , you have to use filters for this
filtering-escaping-post-data-from-injection-attacks
PDO Documentation
MySQLi Documentation
And this is all pure PHP5 concept.
$mysqli = new mysqli($hostname, $username, $password, $database_name);
if($mysqli->error)
die($mysqli->error);
$mysqli->query("SET NAMES 'UTF8'");
$query = "INSERT INTO my_table VALUES ('value_1', 'value_2')";
$mysqli->query($query);
if(!$mysql->error)
echo 'do something';
$query = "SELECT * FROM my_table";
$sql = $mysqli->query($query);
if($sql->num_rows > 0) {
while($row = $sql->fetch_assoc()) {
echo $row['field_1'];
}
}
$sql->close();