I have this php code:
$query = $database->query("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID')";
if($query == 0){
echo "not registered";
}elseif($query == 1){
echo "registered"
}
If I'm not wrong, the query is suppose to return 0 or 1 and it works in my SQLite manager. What is the correct way on getting that value in Php and use it in IF ELSE statement?
If you only need a single value, you can use querySingle:
$result = $database->querySingle("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID'");
Otherwise, with normal queries, the result returned by ->query isn't actually the data itself, but an identifier you would use to get data from the database:
$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}
Related
I'm creating a mobile library app, and for one function of the app I am trying to receive the bookID for all books checked out by a certain user. I would like to be able to echo back the results from the query in a string format (preferably with spaces in between each separate book id) so I can deal with the data later on within the app.
Many of the answers I have found online have simply shown how to execute the query, but not how to use the data afterwards. Sorry if this is a simple question to answer, I am a huge novice.
<?php
require "conn.php";
$email = $_POST["email"];
$mysql_qry = "SELECT * FROM user_data WHERE email like '$email'";
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID LIKE $user_id ORDER BY bookID DESC";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$result2 = mysqli_query($conn, $mysqlqry2);
}
else
{
echo "Error, user name not found";
}
$conn->close;
?>
You could append your results into an array and display values using implode():
<?php
require "conn.php";
$email = $_POST["email"]; // You may test here : if (isset($_POST['email']))
$mysql_qry = "SELECT * FROM user_data WHERE email = '$email'";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID = $user_id ORDER BY bookID DESC";
$result2 = mysqli_query($conn, $mysql_qry2);
if(mysqli_num_rows($result2) > 0)
{
$ids = [];
while ($row = mysqli_fetch_assoc($result2)) {
$ids[] = $row['bookID'] ;
}
echo implode(" ", $ids) ; // print list of ID
}
else
{
echo "No books checked out!";
}
}
else
{
echo "Error, user name not found";
}
$conn->close;
NB: I used your code here, but, you should have to look to parameterized queries to prevent SQL injections.
Your query $mysql_qry2 should be defined after to get $user_id.
Your LIKE $user_id could be replaced by =.
First thing first, always sanitize your data:
$email = filter_var( $_POST['email'], FILTER_SANITIZE_EMAIL );
$user_id = preg_replace( "#[0-9]#", '', $row['user_id'] );
Use
DISTINCT bookID instead of DISTINCT(bookID)
From your query: $mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY bookID DESC";
If you're not getting any result or the returned result is empty but the user_id does exist, then I think the query format is wrong.
What you should do instead
Change the ORDER BY: The query may be correct but mysql returned an empty result because the result order does not match.
Try this
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY userID DESC";
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY `primary_key_here` DESC";
Replace <strong>`primary_key_here`</strong> with the primary key name.
Run the query without conditionals and inspect the result
$query = mysqli_query( $conn, "SELECT bookID FROM books_checked_out DESC" );
var_dump( $query );
Use the result to inspect the rest of the query.
Rather than using your own protocol/format use something like JSON or xml in your response to the request.
This will give you better maintainability in the long run and allow you to easily handle the response in the browser with javascript, and most browsers will give you a nice display of JSON objects in the dev console.
You'll have to extract the user id from the result of the first query or you could do a joined query instead.
$email = validate($POST['email']); //where validate() will try to prevent sql injection
//joined query
$query =
" SELECT bookID FROM user_data
INNER JOIN books_checked_out on user_data.user_id = books_checked_out.userID
WHERE user_data.email='$email'
";
//not sure whether that should be user_id or userID looks like you have mixed conventions
//books_checked_out.userID vs user_data.user_id ... check your database column names
//loop through results
// may be empty if user email doesn't exist or has nothing checked out
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$response[] = ['bookID'=>$row['bookID']];
}
echo json_encode($response);
When receiving the result in php you can use json_decode() or in javascript/ajax it will automatically be available in your result variable.
if things aren't working as expected it can be a good idea to echo the actual sql. In this case
echo 'SQL IS: '.$query;
and test it against your database directly (phpmyadmin/MySQL-Workbench) to see if you get any results or errors.
Something is wrong with my php,
I'm doing an account validation where if the data exist it will display "There is data" and else "No data"...
When I enter the first 'row' reference_id and submit, it shows "There is data" which is correct but when I entered the second to the last 'row' reference_id it shows "No data" even though it exist in my Database!
Database:
reference_id (varchar 250)
status (varchar250)
PHP
if (isset($_POST['submit_valid'])) {
if (!empty($_POST['reference_id']))
{
$query = mysqli_query($con, "SELECT * FROM client_record");
$result = mysqli_fetch_array($query);
if ($result['reference_id'] == $_POST['reference_id'])
{
echo"<script type='text/javascript'> alert('There is data'); window.location.href='next_page.php'; </script>";
}
if ($result['reference_id'] !== $_POST['reference_id']) {
echo"<script type='text/javascript'> alert('No data.'); window.location.href='this_page.php'; </script>";
}
}
}
I am not sure if it's the mysqli_fetch_array fault or the if-else condition is wrong?
if you guys know the problem please help me?
Your query execution currently only looks at the first row. A fetch needs to be looped to iterate over all rows. e.g.
$query = mysqli_query($con, "SELECT * FROM client_record");
$result = mysqli_fetch_array($query);
should be
$query = mysqli_query($con, "SELECT * FROM client_record");
while($result = mysqli_fetch_array($query)) {
but this is inefficient. When looking for a specific record use a where clause. Parameterized queries also will prevent SQL injections, and quoting issues. The i in the bind_param is for an integer, if your id is a string use s.
$prepared = mysqli_prepare($con, "SELECT * FROM client_record where reference_id = ?");
mysqli_stmt_bind_param($prepared, 'i', $_POST['reference_id']);
mysqli_stmt_execute($prepared);
mysqli_stmt_store_result($prepared);
while (mysqli_stmt_fetch($prepared)) {
$query = mysqli_query($con, "SELECT * FROM client_record");
$result = mysqli_fetch_array($query);
This will give you the first row from the table.
Add a WHERE reference_id = :refid clause?!
Then bind the refid parameter, so as to avoid SQL injection.
Lapiz, the problem is actually with the comparison operator:
($result['reference_id'] == $_POST['reference_id'])
This will check the first reference_id from the returned set in array.
The best way to tackle this would be to use if (in_array(5, $result)) where 5 is the needle and $result is the array haystack.
Because all you are doing is to check if the reference exists in the returned data set .
This is also good design practices, to collect results and avoid multiple reference queries each time, hit the database once and query the result set.
If its a multidemnsional array loop through the set:
foreach($result as $resultItem)
{
if(in_array("reference_id", $resultItem, true))
{
echo "There is Data";
}
}
Good Luck .
I created a mysql query to check if user is banned or not and if he's the system give him return false. But it wont get the information.
public static function checkban($username)
{
if(LOGINCHECKBAN == false)
{
$vusername = engine::securyt($username);
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$getNOW = mysql_query($getIdBYname);
$IDbyNAME = mysql_free_result($getIdBYname);
$queryforban = mysql_query("SELECT * FROM bans WHERE data = '".$IDbyNAME."' LIMIT 1");
$query = mysql_num_rows($queryforban);
if($query == 0) {
return true;
} else {
return false;
}
}
}
Note: engine::securyt($username) is the form type to get his username when he try to login.
What can be wrong on my code?
edit: I belive that "mysql_free_result" can be the problem, but im not sure what i need to put on replace of it.
mysql_free_result() frees a mysql result set. It does not actually retrieve data from the result.
You will want something like:
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$result = mysql_query($getIdBYname);
$row = mysql_fetch_assoc($result);
if($row) { //a user was found
//$row['id'] is the found user
$result = mysql_query("SELECT COUNT(*) cnt FROM bans WHERE data = '". $row['id'] ."' LIMIT 1");
$row = mysql_fetch_assoc($result);
return ($row && $row['cnt'] == 0);
} else {
// no user; return something appropriate
}
However, if all you need is to determine is whether a particular user name is banned (and not actually get their user id), you can do that directly in the database with one query:
SELECT COUNT(*)
FROM players p
INNER JOIN bans b ON b.data = p.id
WHERE p.username = $username;
WARNING: Note that using mysql_* functions is strongly discouraged for new code (since mysql_* has been removed in PHP 7), and directly including variables in your query strings is a pretty major security vulnerability. You should look into using prepared statements/parameterized queries with mysqli or PDO.
I've found several tutorials which have similar code like the following:
$sql = "select * from users";
$result = $conn1->Execute($sql);
if ($result==false) {
print 'error' . $conn1->ErrorMsg() . '<br>';
} else {
print_r($result->GetRows());
}
But how can $result ever be false? If I add a where clause which can not be fulfilled the else-branch is still taken since $result contains the column titles. Examples:
"select * from users"; // Select the whole table data
echo "$result";
leads to
id,username,password 1,peter,geheim 2,sabine,secret 3,thorsten,qwertz
Whereas
"select * from users where username = 'does not exist'";
echo "$result";
leads to
id,username,password
Therefore result is never false. What is my mistake here?
The Execute method returns false if the query itself fails, and not if it has 0 results.
If you want to check if the query returned any results you can use the RecordCount method.
$rows = $conn1->Execute($sql);
if ($rows->RecordCount() > 0) {
// Do something with your rows
} else {
// Nothing returned
}
I'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}