I am trying to fetch data from the database, but not retrieve data particular id.
this is my one page:
example1.php
<a style="color: #3498DB;" class="btn btn-default" href="http://www.example.com/getafreequote?id=<?php echo $row['product_id']; ?>">Get Quote</a>
example2.php
<?php
$id = isset($_GET['id'])?$_GET['id']:'';
$query = "SELECT * FROM oc_product_description WHERE product_id=$id";
$run1 = mysql_query($query);
while ($fetch1 = mysql_fetch_object($run1)){
?>
<div class="col-xs-12 col-sm-6">
<label for="GetListed_product"></label>
<input class="le-input" name="product" id="GetListed_product" type="text" value="<?php
$b = $fetch1->product_id;
$q2 ="SELECT product_id,name FROM oc_product_description WHERE product_id = $b";
$q3 = mysql_fetch_assoc(mysql_query($q2));
echo $q3['name'];
?>" >
<span id="productmsg" class="msg"></span>
</div>
<?php
}
?>
</div>
but didnot get data form particular product id. I have got error show like this
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in example.com/example2.php on line 71
Please don't use mysql functions they are deprecated. Use mysqli or PDO for database operations. Also the way you write the query string makes it easy for an SQL injection, use prepared statements instead. Here is an example:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch();
You can also use prepared statements for inserting or updating data. More examples here
As said by FilipNikolovski, don't use mysql functions they are deprecated. Use mysqli or PDO for database operations.
For your problem, the function mysql_query is returning false. The query is not returning any result and thus mysql_query is returning false.
Make a check like this:
$query = "SELECT * FROM oc_product_description WHERE product_id=$id";
$run1 = mysql_query($query);
if($run1)
{
if(mysql_num_rows($run1) > 0)
{
while ($fetch1 = mysql_fetch_object($run1))
{
// your stuff here
}
}
else
{
echo "No records found.";
}
}
else
{
echo "Error in query : ".mysql_error();
}
This will help you to detect the problem and to solve as well.
Related
I have a SQL query in my code that I want to convert to a prepared statement to stop vulnerabilities like SQL injections. So this is what I want to convert:
<?php
$query = "SELECT * from `wp_posts` WHERE ID=$pid ";
$result = mysqli_query($link, $query);
//$id=$row['Gallery_Id'];
while($row = mysqli_fetch_array($result)){
?>
<h2 align="center"> <?php echo $row['post_title']; ?> </h2><br>
<div class="paracenter">
<p id="cont"><?php echo $row['post_content']; ?></p>
<hr color="black" width="10%">
</div>
<?php } ?>
This is what I tried, but it doesn't work.
$query = "SELECT * from `wp_posts` WHERE ID=? ";
$stmt = mysqli_prepare($link, $query);
if($stmt){
mysqli_stmt_bind_param($stmt, "i", $pid);
mysqli_stmt_bind_result($stmt, $dbpid);
mysqli_stmt_execute($stmt);
mysqli_stmt_fetch($stmt);
}
$result = mysqli_query($link, $query);
//$id=$row['Gallery_Id'];
while($row = mysqli_stmt_fetch($result)){
?>
<h2 align="center"> <?php echo $row['post_title']; ?> </h2><br>
<div class="paracenter">
<p id="cont"><?php echo $row['post_content']; ?></p>
<hr color="black" width="10%">
</div>
<?php } ?>
Almost all the examples online doesn't use the procedural method I use. How can I rectify this?
To protect your query against injection attack, you have two options. The first is super simple and just as secure as a prepared statement.
Cast $pid as an integer.
$query = "SELECT post_title, post_content FROM wp_posts WHERE ID = " . (int)$pid;
Secure and done.
How to write a prepared statement with result binding... (I don't use procedural mysqli syntax)
if (!$stmt = $link->prepare("SELECT post_title, post_content FROM wp_posts WHERE ID = ?")) {
echo "Syntax Error # Prepare"; // $link->error; <-- never show actual error details to public
} elseif (!$stmt->bind_param("i", $pid) || !$stmt->execute() || !$stmt->bind_result($title, $content)) {
echo "Syntax Error # ParamBind | Execute | ResultBind"; // $stmt->error; <-- never show actual error details to public
} else {
while ($stmt->fetch()) {
echo "<div>";
echo "<h2 align=\"cente\">$title</h2><br>";
echo "<div class=\"paracenter\">";
echo "<p id=\"cont\">$content</p>";
echo "<hr color=\"black\" width=\"10%\">";
echo "</div> ";
}
}
Some additional notes.
If you are not going to use result binding, you should use mysqli_fetch_assoc() instead of mysqli_fetch_array(). mysqli_fetch_array() will generate a bloated result set of both indexed and associative keyed elements (double what you actually need).
When you use bind_result(), you need to replace * in the SELECT clause with the columns to be extracted.
My first elseif() expression contains three separate calls & checks on $stmt. As soon as any one of those calls returns a falsey/erroneous response, the conditional expression short circuits and the remaining calls in the expression are never executed.
If adopting my object-oriented mysqli style, be sure to align your database connection syntax as object-oriented as well.
I'm trying to make this code work but I don't know why it won't. Basically I want it to display a name if the nickname column in the database is null. And if it's not null it should display the nickname. Also I'm somewhat noob so keep that in mind when responding.
$namn = mysql_query("SELECT name FROM Horseinfo WHERE name = '$somevariable'");
$nicknamn = mysql_query("SELECT nickname FROM Horseinfo WHERE name = '$somevariable'");
<? $row = mysql_fetch_array($nicknamn,$namn);
if(is_null($nicknamn)) {?>
<div style='font-size:18px; padding-bottom:3px; margin-top:0px;'>records for <? echo $row['name'];?></div>
<?} else {?>
<div style='font-size:18px; padding-bottom:3px; margin-top:0px;'>records for <? echo $row['nickname'];?></div>
<?}?>
Based on assumption I would say that your nickname column does not contain a database NULL value, rather it would be an empty string instead (this totally depends on the routine filling the Horseinfo table). You also only need one SQL query to fetch both name and nickname.
My suggestion would be to use empty() instead:
// try to use mysqli_* instead of mysql_* functions, mysqli_query() expects parameter 1 to be a database connection resource
$res = mysqli_query($connection, "SELECT name, nickname FROM Horseinfo WHERE name = '$somevariable'");
if ($res && mysqli_num_rows($res)>0) {
$row = mysqli_fetch_row($res);
$horseName= empty($row['nickname']) ? $row['name'] : $row['nickname'];
?>
<div style='font-size:18px; padding-bottom:3px; margin-top:0px;'>records for <? echo horseName;?></div>
<?php } ?>
I have been trying for a while to figure out how to display data from a specific row within my database based on the ID.
Say I want the link to be survivaloperations.net/page/mso?p=contracts&id=#
where id=# is the ID of the row I am pulling data from in the database
How would I pull and display data from the database using a link like shown above?
I Tried to google it, but didn't really know what to google to find related things
Any help or links for references are appreciated!
Here is what I had tried:
<?php
if ($p == contracts) {
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0; // if $_GET['id'] exists, return it as an integer, otherwise use a sentinel, id's usually start with 1, so 0 works
if ($id != 0):
// I assume this is a specific news item meaning you know it's ONE result
$query = 'SELECT * FROM contracts WHERE id=' . $id . ' LIMIT 1'; // so try to use limit 1, no need to add extra steps in the database lookup
endif;
mysql_select_db('survival_contracts');
$result = mysql_query($query);
//$result = mysql_query($query) or die(mysql_error());
// now loop through the results
while ($row = mysql_fetch_array($result)) {
// and use'em however you wish
echo("<div class='mso_body_wrap'>
<div id='mso_news_container'>
<div class='mso_news_wrap'>
<div class='mso_news_top'>$row2[contract_type]</div>
<div class='mso_news_poster'>
<div class='mso_poster_avatar'><img src='images/tank.jpg'></div>
<div class='mso_poster_info'>for <a
href='#'>$row2[unit]</a><br/>by: <a
href='http://www.survivaloperations.net/user/$row2[userid]-$row2[username]/'>$row2[username]</a>
</div>
</div>
<div class='mso_news_content'>
<div class='mso_news_body'>
Callsign: $row2[callsign]<br/>
Urgency: $row2[urgency]<br/>
Location: $row2[location]<br/>
Grid: $row2[grid]<br/>
Enemy Activity: $row2[enemy_activity]<br/>
Hours Since Lasrt Contact: $row2[contact_hours]<br/><br/>
Supplies Requested: $row2[supplies]<br/>
Comments: $row2[comments]
</div>
</div>
<div class='mso_news_bottom'></div>
</div>
</div>");
}
?>
I figured it out with my original code:
if ($p == contracts)
{
$cid = $_GET['id']; // if $_GET['id'] exists, return it as an integer, otherwise use a sentinel, id's usually start with 1, so 0 works
$query = 'SELECT * FROM contracts WHERE id='. $cid .' LIMIT 1'; // so try to use limit 1, no need to add extra steps in the database lookup
mysql_select_db('survival_contracts');
$result = mysql_query($query);
//$result = mysql_query($query) or die(mysql_error());
// now loop through the results
while($row = mysql_fetch_array($result)){
// and use'em however you wish
echo ("<div class='mso_body_wrap'>
<div id='mso_news_container'>
<div class='mso_news_wrap'>
<div class='mso_news_top'>$row[contract_type]</div>
<div class='mso_news_poster'>
<div class='mso_poster_avatar'><img src='images/tank.jpg'></div>
<div class='mso_poster_info'>for <a href='#'>$row[unit]</a><br />by: <a href='http://www.survivaloperations.net/user/$row[userid]-$row[username]/'>$row[username]</a></div>
</div>
<div class='mso_news_content'>
<div class='mso_news_body'>
Callsign: $row[callsign]<br />
Urgency: $row[urgency]<br />
Location: $row[location]<br />
Grid: $row[grid]<br />
Enemy Activity: $row[enemy_activity]<br />
Hours Since Lasrt Contact: $row[contact_hours]<br /><br />
Supplies Requested: $row[supplies]<br />
Comments: $row[comments]
</div>
</div>
<div class='mso_news_bottom'></div>
</div>
</div>");
}
Google for $_GET variable in PHP and have a look at database connection using PDO or mysqli
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/pdo.query.php
After you added code:
mysql_* is deprecated. Try to switch to either mysqli or PDO and have a look at the link above.
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT) ? abs( (int) $_GET['id']) : 0;
if($id == 0) {
echo 'Invalid ID';
return;
} else {
$query = "SELECT * FROM `table` WHERE `id`=". $id;
$get = $db->prepare($query);
if($get) {
$get = $db->query($query);
$r = $get->fetch_array(MYSQLI_ASSOC);
var_dump($r);
} else {
echo 'Could not connect to the database';
return;
}
I've mixed two styles of MySQLi, which isn't really standard, but it should suffice for this example.
http://php.net/mysqli
(Ensure you have database connection)
$row2 should be $row
And things like
$row[contract_type]
Better to be
$row['contract_type']
And try to move to mysqli or PDO as advised by earlier poster
Am sorry for the really stupid question. i have a code like so and i would like the result to be done on a while loop. i was using mysql befor and the query was simple and executed well.
example
$sql_query = mysql_query($query);
while($row = mysql_fetch_array($sql_query)
{
$data_a = $row['a']; $data_b = $row['b'];
}
now i use oop and i have a database class and a connection handler that is injected in to the new class am extending from the database class. my proble no is after the code executes, i get this error method *mysqli_stmt::fetch_assoc()* here is my code
<?php
class recentWorks extends DatabaseModelBase
{
public function show($tbl, $num_to_show, $site_url="")
{
$statement = $this->prepare('SELECT * FROM '.$tbl.' WHERE RAND()<(SELECT (( '.$num_to_show.' /COUNT(*))*10) FROM '.$tbl.' ) ORDER BY RAND() LIMIT '.$num_to_show.' ');
$statement->execute();
while ($recent_results = $statement->fetch_assoc())
{
$featured_work_name=$recent_results['name']; $featured_work_url=$recent_results['url']; $featured_work_thumb=$recent_results['img_thumb'];
$featured_work_id=$recent_results['id'];$featured_work_desc=$recent_results['desc'];$featured_work_img=$recent_results['img_url'];
?>
<li>
<a href="<?php echo $featured_work_img; ?>" class="fancybox thumb poshytip" title="Click To View Enlarged Image">
<img src="<?php echo $featured_work_thumb; ?>" width="282px" height="150px" alt="<?php echo $featured_work_name; ?>' Image" />
</a>
<div class="excerpt">
<span class="main_header"><?php echo ucwords($featured_work_name); ?>
</span>
<?php echo substr($featured_work_desc,0,300); ?>
</div>
</li>
<?php
}
$statement->close();
}
}
?>
please someone debug this for me
Let's see what you had before
$sql_query = mysql_query($query);
`----- missing error checking and handling
while ($row = mysql_fetch_array($sql_query))
`---- missing error handline
{
$data_a = $row['a']; $data_b = $row['b'];
`----- complicated way of setting variables as arrays
}
Now let's see what you have now (selected lines)
$statement = $this->prepare('SELECT * FROM '.$tbl.' WHERE RAND()<(SELECT (( '.$num_to_show.' /COUNT(*))*10) FROM '.$tbl.' ) ORDER BY RAND() LIMIT '.$num_to_show.' ');
`---- using prepare as if it would have been mysql_query()
$statement->execute();
`----- same here
This is wrong. Just telling you. I suggest you search for some well-working mysqli_* tutorial first. One that either explains you how to build SQL queries and fire them and that explains what prepared statements are and how to use them.
My suggestion: Start with the PHP manual, it compares the different libraries and shows examples for all mysql, mysqli and PDO.
You have even a comparison side-by-side of mysql and mysqli for a more easy migration: Dual procedural and object-oriented interface.
I'm learning PHP from reading the php manual and studying different tutorials. I hit a snag with the mysql_query. I'm trying to insert user data into a database from a form using PHP. The mysql_query should return false because the username doesn't exist in the database yet but according to the result I am getting it is returning true and nothing is being entered into the database. Am I using mysql_query wrong or is using !result incorrect?
$sql = "SELECT * FROM users WHERE username='".$_POST["name"]."'";
$result = mysql_query($sql)
if (!$result) {
$sql = "INSERT INTO USERS (username, email, password) VALUES
('".$_POST["name"]."', '".$_POST["email"]."', '".$passwords[0]."')";
$result = mysql_query($sql);
if ($result) {
echo "It's entered!";
} else {
echo "There's been a problem: " . mysql_error();
}
} else {
echo "There's already a user with that name: <br />";
$sqlAll = "SELECT * FROM users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
}
}
Jason, you're checking to see if the query has failed or not - not whether it has returned the value 'false' or 'true'. You need to call mysql_fetch_row or similar, then compare the result.
Alternatively you could use the following:
if (mysql_num_rows($result) == 0) {
/* User doesn't exist */
} else {
/* User exists */
}
This will detect if any users have been chosen by your query and - if they have - your user exists already.
Also, you should learn about input sanitisation and SQL Injection. It's a very critical security issue and your script is vulnerable to it. More info here.
A select query which has no result rows STILL returns a result handle. msyql_query() will ONLY return a 'false' value if the query fails due to a syntax error, constraint violation, etc...
Your code should be
$sql = "...";
$result = mysql_query($sql);
if ($result === false) {
die("QUery failed: " . mysql_error());
}
if (mysql_num_rows($result) == 0) {
... user does not exist ...
}
And please please please read up about SQL injection vulnerabilities. Your code has holes wide enough for a truck to drive through.
In this case, $result will be a resource. You should check the number of results with mysql_num_rows().
Never, really, NEVER, use $_POST or any direct user input in a query. Always escape the input, BEFORE using it in a query, with mysql_real_escape_string(), or you'll have opened a serious security issue with SQL Injection.
Ex:
$safe_name = mysql_real_escape_string($_POST["name"]);
$sql = "SELECT * FROM users WHERE username='$safe_name'";
It's not exact.
mysql_query() will also fail and return FALSE if the user does not
have permission to access the table(s) referenced by the query.
In your case you have the permission but the user doesn't exist. So it will return true but the result set returned is empty.
mysql_query will return an empty set if the query returns no data. The query will however not fail.
i solve my problem :
like this
<?php
$username = $_POST['username'];
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
while($row = mysqli_fetch_array($result)){
echo $row['username'];
echo "</br>";
echo "</br>";
echo "<p><b>Secret Question</b></p>";
echo $row['secret'];
}
?>
</br>
</br>
<form action="forgetaction.php" method="POST">
<p><b>Answer is :</b><p>
<input type="hidden" name="username" value="<?php echo $username; ?>">
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit">
</form>
and forget action.php like this :
<?php
include('config.php');
$username = $_POST['username'];
echo $username;
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
$row = mysqli_fetch_array($result);
if($row['answer'] == $_POST['answer']) {
echo $row['password'];
} else {
echo 'wrong!';
}
?>
thank you all for help .