I want to get the first name, last name and county to display but I am getting errors when I try to concatenate the echo statement here. How can I correct this?
$query = mysql_query("
SELECT `first_name`, `last_name`,`county`
FROM `contact`
WHERE `first_name` ='". mysql_real_escape_string(trim($_POST['name'])) ."'
");
echo (mysql_num_rows($query) !== 0)? mysql_result($query,0,'first_name'):'Name not found';
?>
This is the message I receive:
Warning: mysql_result(): last_name.county not found in MySQL result index 5 in C:\xampp\htdocs\ajax_Contact\name.php on line 14
This code should answer the OP's question in relation to his current code:
$query = mysql_query("
SELECT `first_name`, `last_name`,`county`
FROM `contact`
WHERE `first_name` ='". mysql_real_escape_string(trim($_POST['name'])) ."'
");
(mysql_num_rows($query) !== 0) ? print mysql_result($query,0,'first_name') : print 'Name not found';
?>
Also according to your error, make sure that this line:
`last_name`,`county`
is not currently
`last_name`.`county`
Notice the comma/period difference.
OR, if you are trying to display first name, last name, and county use this:
$query = mysql_query("
SELECT `first_name`, `last_name`,`county`
FROM `contact`
WHERE `first_name` ='". mysql_real_escape_string(trim($_POST['name'])) ."'
");
(mysql_num_rows($query) !== 0) ? print mysql_result($query,0,'first_name')." ".mysql_result($query,0,'last_name')." ".mysql_result($query,0,'county') : print 'Name not found';
?>
And ultimately for better performance and supported code use
$mysqli = new mysqli("your_host", "your_user", "your_password", "your_database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "
SELECT `first_name`, `last_name`,`county`
FROM `contact`
WHERE `first_name` ='". mysql_real_escape_string(trim($_POST['name'])) ."'
";
$result = $mysqli->query($query);
while($row = $result->fetch_array()){
$rows[] = $row;
}
if($result->num_rows === 0){
print 'Name not found';
}
foreach($rows as $row){
print $row['first_name']." ".$row['last_name']." ".$row['county'];
}
/* free result set */
$result->close();
/* close connection */
$mysqli->close();
Your easyest way is to use a newer version of the MySQL functions - mysqli is a very good one to go with. But if you have to rely on the old function set, then pleace read the documentation; mysql_result returns the data, and you should prepare it yourself in the code.
Also, I have to agree with #MarcB - use mysql_fetch_assoc or something like that when oyu are only and really expecting one single row.
But if you have the time, merge to the mysqli or PDO methods - they are more modern (in other words they are OOP all the way) and safer.
First, don't use the mysql_*() library. It's deprecated and obsolete. But if you have to use it, then DON'T use mysql_result. It's inefficient. A better process is to fetch an entire row using the fetch functions
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($row);
if (mysql_num_rows($result) != 0) {
echo $row['first_name'], $row['last_name'], $row['county'];
}
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 am trying to insert to another table the results of a select statement from another table. The select statement works but the insert statement does not work. Please help me.
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
}
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
header("Location:homeclient.php");
?>
You asked for how to do these two as one query.
This is how:
$query = mysql_query("INSERT INTO `client` ( `client_csub_code`, `client_csub_name`, `client_csub_day`, `client_csub_time` ) SELECT `sub_code`, `sub_name`, `sub_day`, `sub_time` FROM `subject` WHERE `code` = '$enrol'");
// I would also add error checking
if ( mysql_errno() )
echo mysql_error();
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
}
header("Location:homeclient.php");
?>
Try changing to this. Currently your query is outside of your while, it will only run once and the values of $csubject etc are always going to be the last values of your fetched results.
Purpose of this query is to retrieve a true image plus 3 random generated images from same table, then show them randomly. User(child) have to select correct image.
Thanks
$sql= "SELECT * FROM `login` WHERE `user` = '$word'";
" UNION"
"SELECT * FROM `login` WHERE `user` != '$word' ORDER BY RAND() LIMIT 3";
$row2=mysql_query($sql);
$i=1;
while ($r = mysql_fetch_array($row2))
{
echo '<td> ';
echo '<img src="sigg/'.$r['img'].'" width="130" height="130" /><br>';
echo $r['user'];
echo '</td>';
$i++;
}
Use the UNION clause:
$sql = "(SELECT * FROM `login` WHERE `user` = '$word')";
$sql.= " UNION";
$sql.= " (SELECT * FROM `login` WHERE `user` != '$word' ORDER BY RAND() LIMIT 3)";
$sql.= " ORDER BY RAND()";
To get the results you can use for example MySQLi (poseted before OP added his code with mysql_* functions):
$MySQL=new mysqli("localhost", "username", "password", "database");
$query = $MySQL -> query($sql);
while ($entry = $query -> fetch_row())
{
// $entry is an array with the results, use for example:
echo $entry[0]; // will return the first column of your table
echo $entry[1]; // will return the second column of your table
// try also:
var_dump($entry); // outputs everything for testing purposes
}
Please, don't use the mysql_* functions, they are deprecated and will be removed in the future versions of PHP. Use MySQLi or PDO instead. See Why shouldn't I use mysql_* functions in PHP? for more details.
Your request is not clear enough to provide a solid answer, so I'll try to answer it the best I can.
You should use Union in your query to get one big list of entries. However, just doing
SELECT * FROM `login` WHERE `user` = '$word'
UNION
SELECT * FROM `login` WHERE `user` != '$word' ORDER BY RAND() LIMIT 3
will give you a list of entries where user = $word in the first part and random 3 other entries.
As I said, I don't know the exact purpose of this, but I think you're better of querying the entire list from your database server.
Here's the php code:
$connection = mysql_connect(HOST, USER, PASSWORD);
mysql_select_db(DATABASE_NAME, $connection);
$sql = "SELECT img, user FROM `login` WHERE `user` = '{$word}' UNION SELECT img, user FROM `login` WHERE `user` != '{$word}' ORDER BY RAND() LIMIT 3";
$results = mysql_query($sql, $connection);
$rows = array();
// Insert results in a new array to shuffle it
while ($row = mysql_fetch_array($results)) {
$rows[] = array(
'img' => $row['img'],
'user' => $row['user']
);
}
shuffle ($rows); // Randomize order
// Construct HTML
$html = '';
foreach ($rows as $entry) {
$html .= '<td><img width="130px" height="130px" src="sigg/' . $entry['img'] . '">
$html .= $user . '</img></td>';
}
echo $html;
You will need to replace capitalized words with what's necessary.
A few explanations:
replace * with only what you need from tables (use fewer memory)
first insert results in an array so you can randomize the order (from MySQL you'll always have the first line the results from first query)
construct the html and output it all at once (executing multiple echo relies on the buffering to not send it to the browser, but that option might be off: What is output buffering).
I think this should work but it is not...
Basically i am trying to check mysql db to see if there is a record that meets the 2 variables..if no do one thing if yes do another thing. the result is always no at this point.
$result = mysql_query("SELECT 'lastname' FROM 'Cust_Releases' WHERE 'lastname' = '$usercheck' AND 'TripID'= '$RLtripid'");
echo $result;
if(mysql_num_rows($result) == 0) {
echo"no";// row not found, do stuff...
}
else {
echo"yes"; // do other stuff...
}
First of all, stop using mysql_* functions because this extension is deprecated as of PHP 5.5.0.
Second always use the (`) symbol around database names, table names and column names.
You have a reserved word used RELEASE.
$sql = "SELECT `lastname` FROM `Releases` WHERE `lastname` = '$usercheck' AND `TripID` = '$RLtripid'";
Reserved words you find here
$result = mysql_query("SELECT lastname FROM `Releases` WHERE lastname = '$usercheck' AND TripID= '$RLtripid' LIMIT 1");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
echo $result;
if(mysql_num_rows($result) == 0) {
echo"no";// row not found, do stuff...
}
else {
echo"yes"; // do other stuff...
}
Escaping 'Releases', as Bondye suggested
Adding 'LIMIT 1' to your query to allow the possibility of an early-out when there is more than one matching record. You don't appear to need the total count. May not make any difference if unique constraints exist which guarantee that only one row can be returned
mysql_query is deprecated. In real code you should be using PDO and prepared statements / bind variables!
debugging is a very important thing in programming. first do make sure that the varibales $usercheck, and $RLtripid contain values.
-----------------------
$sql = "SELECT `lastname` FROM `Cust_Releases` WHERE `lastname` = '$usercheck' AND `TripID`= '$RLtripid'";
echo $sql;
$result = mysql_query($sql);
....-------------------
Try this code. It will help you
$result = mysql_query("SELECT COUNT( * ) from Cust_Releases lastname = '$usercheck' AND TripID= '$RLtripid'");
if($result == 0) {
echo"no";// row not found, do stuff...
}
else {
echo"yes"; // do other stuff...
}
I want to show the maximum value of a particular column of mysql table in php. Here is my code:
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$var = $_POST['value'];
$sql = mysql_query(" SELECT MAX(column) FROM tableName WHERE variable='$var' ") or die(mysql_error());
$row = mysql_fetch_array($sql) or die(mysql_error());
echo "Maximum value is :: ".$row['column'];
?>
output:::
Maximum value is ::
Or you could be a bit creative:
$sql = mysql_query("SELECT `column` FROM tableName WHERE variable='$var' ORDER BY `column` DESC LIMIT 1") or die(mysql_error());
This is the same problem that I was searching for a solution. The approach below worked. The solution was using "MYSQLI_NUM". While the code below gives the intended result it still seems way too complex. Is there a way to "short-cut" using the "while" statement to search an array since there is only one returned value?
Selecting a max value only returns one number, yet PHP still seems to require a loop to evaluate an entire array. I was expecting something easy, like: max_value=result(0).
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error.' Sorry, could not connect to the database server');
$query = "SELECT MAX(IssueIDNUM) FROM tblIssueList";
$result =$conn->query($query);
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
$maxresult=$row[0];
echo $maxresult;
}
$result->close();
$conn->close();
?>
With further experimentation, I was also able to adapt the code by Jim H. to develop the following solution. Though it works the code still seems too complex.
// Solution #2
$result =$conn->query("SELECT MAX(IssueIDNUM) `max` FROM tblIssueList");
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo $row['max'];
}
The real name of column is MAX(column), try:
print_r($row);
You may either do:
$sql = mysql_query(" SELECT MAX(column) AS `column` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Or:
$row = mysql_fetch_row($sql) or die(mysql_error());
echo "Maximum value is :: ".$row[0];
You have two choices. By Index or by Column Name. If you really want to use a column name, alias the column in your query.
$sql = mysql_query(" SELECT MAX(column) `max` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Then you can use
$row['max'];
or
$row[0];
You are probably not returning any rows. You should try WHERE variable LIKE '%$var%';
$sql = mysql_query(" SELECT MAX(column) AS GIVE_A_NAME FROM tableName WHERE variable='$var' ") or die(mysql_error());
and
echo "Maximum value is :: ".$row['GIVE_A_NAME'];