I have this code. In the first query I want it to select a pid. Then I want to somehow use the selected pid as WHERE in the second query. This do not work but I want it to work on this(the same) page. I have read about this on other forums but I still didn't fix it. Probably a small mistake somewhere.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$loggedInUserId = $_SESSION['user_id'];
$resu = mysql_query("SELECT pid FROM users WHERE id='$loggedInUserId';");
$ro = mysql_fetch_row($resu);
$sql= "SELECT pid, project_name, image, image_type FROM project WHERE pid ='". $row["pid"]. "';";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
//$type= "Content-type:".$row['image_type'];
//header ($type);
echo "<form action='respodents.php' method='post'><button name='submit' id='projectbutton'>
<div>
<img src=pic.php?pid=".$row['pid']." width=100px height=100px/>"." <div id='project_name'>".$row['project_name']."</div>"."
<input type='hidden' name='pid' value='".$row['pid']."'>
<input type='hidden' name='project_name' value='".$row['project_name']."'>
</div>
</button></form>";
}}
mysqli_close($mysqli);
?>
With respect to the sql, perhaps this might work
SELECT `pid`, `project_name`, `image`, `image_type`
FROM `project` WHERE `pid` = (
SELECT `pid` FROM `users` WHERE `id`='$loggedInUserId'
);
The original code had a mix of mysql and mysqli functions with a further mix of Object Orientated and Procedural method calls. Whilst this wouldn't cause an error necessarily it is bad practise to do so. Below is all in a procedural style - it's not tested but it incorporates the two queries into one which should work ( famous last words )
Sidenote: That said - with mysqli you can take advantage of prepared statements which help mitigate against the threat of sql injection - it's quite straightforward to lean and use - so rather than embedding a variable in the sql you would use a placeholder and then bind a variable to that.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
/* db connection? */
if( mysqli_connect_errno() ) echo mysqli_connect_error();
else {
$loggedInUserId = $_SESSION['user_id'];
$sql="select `pid`, `project_name`, `image`, `image_type`
from `project`
where `pid` = (
select `pid` from `users` where `id`='$loggedinuserid'
);";
$resu=mysqli_query( $mysqli, $sql );
if( $resu ){
$ro = mysqli_fetch_row( $resu );
while( $row=mysqli_fetch_object( $resu ) ){
echo "<form action='respodents.php' method='post'>
<button name='submit' id='projectbutton'><!-- you cannot re-use IDs, they MUST be unique! -->
<div>
<img src'=pic.php?pid=".$row->pid."' width='100px' height='100px'/>
<div id='project_name'>".$row->project_name."</div><!-- you cannot re-use IDs, they MUST be unique! -->
<input type='hidden' name='pid' value='".$row->pid."'/>
<input type='hidden' name='project_name' value='".$row->project_name."'/>
</div>
</button>
</form>";
}
}
mysqli_close( $mysqli );
}
?>
First of all, you should not be mixing mysql and mysqli. Let's use mysqli as mysql is deprecated.
I will assume that you don't need it to be in just one query since you never specified.
$result = mysqli_query("SELECT pid FROM users WHERE id='$loggedInUserId';");
while($row = mysqli_fetch_row($result))
{
$pid = $row['pid'];
}
$sql= "SELECT pid, project_name, image, image_type FROM project WHERE pid ='". $pid. "';";
$result = $mysqli->query($sql);
Also, you really should learn to use prepared statements as they are a much safer.
$ro = mysql_fetch_row($resu);
$sql= "SELECT pid, project_name, image, image_type FROM project WHERE pid ='".
$row["pid"]. "';";
$ro = mysql_fetch_row($resu); should be spelled $row not $ro. There's nothing in the variable you are calling in your SQL statement.
Also, your SQL Statement doesn't make much sense in terms of
$row["pid"],
you are accessing a numerical array with mysql_fetch_row(http://php.net/manual/en/function.mysql-fetch-row.php).
If anything, you want to do mysql_fetch_array or mysql_fetch_assoc, to fetch an associative array that you can access the "pid" data statement. The way you are doing it with fetch_row you want to access it numerical, i.e.,
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
The above is copied directly from the php mysql_fetch_row docs.
Edit::
http://php.net/manual/en/mysqli-result.fetch-row.php
Mysqli Docs for fetch_row.
I believe you have to change this code:
$resu = mysql_query("SELECT pid FROM users WHERE id='$loggedInUserId';");
to:
$resu = mysql_query("SELECT pid FROM users WHERE id='".$loggedInUserId."'");
And do not mix mysql and mysqli commands you can easly mess up you code that way.
This looks smelly
$ro = mysql_fetch_row($resu);
$sql= "SELECT pid, project_name, image, image_type FROM project WHERE pid ='". $row["pid"]. "';";
change $ro = mysql_fetch_row($resu); to $row = mysql_fetch_row($resu);
Related
The SQL query returns just Array in the browser even if there is values in the database. I have tried the query in phpmyadmin and it works but not in my php document.
require_once('connect.php');
$query = "SELECT `id` FROM `questions` WHERE round='1' AND year='2016'";
$sql = mysqli_query($dbconnect, $query);
$row = mysqli_fetch_array($sql, MYSQLI_ASSOC);
Almost the same query works in different php documents. Any suggestions what is wrong? Should also say that the query should return integers.
$query = "SELECT `id` FROM `questions` WHERE round='1' AND year='2016'";
You're only selecting the id column. If you wish to echo more columns, then you need to add them in the query.
I.e.:
$query = "SELECT `id`, `col2`, `col3` FROM `questions` WHERE round=1 AND year=2016";
then loop over results:
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)) {
echo $row['id'];
// echo "<br>";
// echo $row['col2'] . "<br>";
// echo $row['col3'];
}
Check for errors on the query also and assuming a successful mysqli_ connection.
http://php.net/manual/en/mysqli.error.php
Other reference:
http://php.net/manual/en/function.mysqli-connect.php
if you want to display other column's data so have to add * in the place of 'id'
require_once('connect.php');
$query = "SELECT * FROM `questions` WHERE round='1' AND year='2016'";
$sql = mysqli_query($dbconnect, $query);
I started programming in php and I'm having a small doubt.
I'm trying to do a search the database using a value from a dropdown.
The problem is that the query always uses the last value of the dropdown.
Does anyone can help me find the error?
Why is research in where clause is always the last value of the dropdown?
Code
<tr><td>Technical:</td><td>
<select>
<?php
$query = "SELECT idTechnical, name FROM technicals";
$result2 = mysql_query($query);
$options="";
while($row=mysql_fetch_array($result2)){
$id=$row["idTechnical"];
$thing=$row["name"];
echo "<OPTION VALUE=$id>$thing</option>";
}
?>
</select>
<?php
if (isset($_POST['Next'])) {
if($_REQUEST['Next']=='Search') {
{
$sql="select idTask, descTask, deadline, idTechnical from tasks where idTechnical = '$id' order by deadline desc";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
}
}
}
?>
I select any value from dropdown, but only uses the last value in clause where :S
Here is what I would do for the form (assuming you have a proper form tag with an action attribute that points to the correct PHP script):
<tr>
<td>Technical:</td>
<td>
<select name="technical">
<?php
$query = "SELECT idTechnical, name FROM technicals";
$result2 = mysql_query($query);
$options="";
while($row=mysql_fetch_array($result2)){
echo '<option value='.$row["idTechnical"].'>
'.$row["name"].'
</option>';
}
?>
</select>
</td>
Then in the PHP script:
$sql='SELECT
idTask,
descTask,
deadline,
idTechnical
FROM tasks
WHERE idTechnical = '.$_REQUEST['technical'].'
ORDER BY deadline DESC';
$result=mysql_query($sql);
$count=mysql_num_rows($result);
This should do it for you.
But please note: The script above is a security risk because it leaves the door wide open for SQL injection
A better way to do this would be to use a PDO Prepared statement, like this:
$db = new PDO('mysql:host=CHANGE_THIS_TO_YOUR_HOST_NAME;
dbname=CHANGE_THIS_TO_YOUR_DATABASE',
'CHANGE_THIS_TO_YOUR_USERNAME',
'CHANGE_THIS_TO_YOUR_PASSWORD');
$sql='SELECT
idTask,
descTask,
deadline,
idTechnical
FROM tasks
WHERE idTechnical = :id
ORDER BY deadline DESC';
$query = $db->prepare($sql);
$query->bindValue(':id', $_REQUEST['technical']);
$query->execute();
$count = $query->rowCount();
If you're just starting in PHP, I would highly recommend that you spend some time to become familiar with PDO Database querying. Good luck and happy coding!
Any ideas why this simple php code won't display results when trying to echo the data.
<?php
{
mysql_connect("localhost" , "" , "") or die (mysql_error());
mysql_select_db("") or die(mysql_error());
$pid=intval($_SESSION["User_id"]);
$query = "SELECT `car`, `details`, `price` FROM `Car``";
//executes query on the database
$result = mysql_query ($query) or die ("didn't query");
//this selects the results as rows
$num = mysql_num_rows ($result);
while($row=mysql_fetch_assoc($result))
{
$_SESSION['car'] = $row['car'];
$_SESSION['details'] = $row['details'];
$_SESSION['price'] = $row['price'];
}
}
?>
<?php echo $_SESSION['car']; ?>
<?php echo $_SESSION['details']; ?>
<?php echo $_SESSION['price']; ?>
Just testing at the moment to see if the car, price and details display from the database and they don't seem to.
You missed session_start(); at start of page and change
$query = "SELECT `car`, `details`, `price` FROM `Car``";
^
to
$query = "SELECT `car`, `details`, `price` FROM `Car`";
Are you expecting one or many results for this query ?
If many results, you are saving the last entry in the session.
If only one, just do : $row=mysql_fetch_assoc($result) instead of this while.
Check the query.Try to echo it, copy, paste in MySQL and run it. But you have $pid, have you put it in the query?
$query = "SELECT car, details, price FROM Car WHERE id = $pid ";
I rather remove all backticks since non of those identifiers are reserved keywords.
$query = "SELECT car, details, price FROM Car";
I'm having a problem with PHP. I want the following code to only show one result from the databse - the one that matches the siteID field. But instead it is returning all of the results from the database.
<?php
$siteID = $_GET['siteID'];
include 'connect.php';
$sql = "SELECT id, siteID,name,description,skills,extra1,extra2 FROM folio";
$queryresult = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($queryresult)) {
$id = $row['id'];
$siteID = $row['siteID'];
$name = $row['name'];
$description = $row['description'];
$skills = $row['skills'];
$extra1 = $row['extra1'];
$extra2 = $row['extra2'];
echo "<div id='title'>
<h5>$name</h5>
</div>
<div id='holder'>
<div id='blogleft'>
</div>
<div id='blogright'>
<p>Archive / Calendar<br /><br /> Add some sort of calendar or archive here; for previous blog posts.</p>
</div>
</div>";
}
?>
the url ends with "/work.php?siteID=pluggedin"
You need a WHERE clause.
$sql = "SELECT id, siteID, name, description, skills, extra1, extra2 FROM folio WHERE siteID='".$siteID."'";
Although i don't recommend this at all. Look up SQL injection if you don't know what I'm talking about. I would do a PDO statement instead.
Something like this:
$sql = "SELECT * FROM folio WHERE siteID=:siteid";
$sth = $dbh->prepare($sql);
$sth->bindParam(':siteid', $siteid, PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
You can also do:
$result = $sth->fetch(PDO::FETCH_ASSOC);
which gives you an array with column names, similar to mysql_fetch_assoc, this will retrieve the next row, again similar to mysql_fetch_assoc.
You didnt used any where condition in your query.
Try this
$sql = "SELECT id, siteID, name, description, skills, extra1, extra2 FROM folio WHERE siteID='".(int)$_GET['siteID']."' ";
$sql = "SELECT
id,
siteID,
name,
description,
skills,
extra1,
extra2
FROM folio
where siteID = $siteID";
You just miss the where clause.
That's because you are selecting all your records in your table ... add a LIMIT clause to your query
Hi please tell me if this is a low resources piece of code, and if it is not how shall I change it ? Thank you!
$query = 'SELECT MAX(ID) as maxidpost
FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$postid = $row['maxidpost']+1;
echo "p=$postid";
The improvement is debatable, but:
$query = 'SELECT MAX(ID) +1 as maxidpost
FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo "p = ". $row["maxidpost"];
You can do math in SQL statements, saving you from having to do the operation in PHP.
It'd be nice to know what you're using this for - if it's the next id to be inserted, using AUTO_INCREMENT would be safer. SELECT statements are generally given higher priority over INSERT/UPDATE/DELETE, and thus can read before an insert from another source -- which would risk duplicates.
Because you are returning one row, you should do something like:
$query = 'SELECT MAX(ID) as maxidpost FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
$postid = $row['maxidpost']+1;
echo "p=$postid";
Otherwise seems about as good as you could do.
You can recalculate the post code after each post. Start with zero. Select it from the database, use that id, add one, save back to database.
Or you could use auto increment (if that is possible).