I was writing the php to query the MySQL DB, but the sql sentence works sometimes but failed sometimes .**when it works, it will return records, when it failed it will say: **You have an error in your SQL syntax. I don't know how to fix it,please give me a hand.thanks.the *_id and type is integer,others are string or date type.
function getMyAwardRecords()
{
global $db, $userId, $nickName;
$result0 = $db->fetchrows("SELECT user_nick,type,create_date FROM records WHERE type=0 AND user_id={$userId}");
// echo $userId;
$result = $db->fetchrows("SELECT records.user_nick, records.type, records.create_date, awards.code FROM records, awards WHERE records.award_id = awards.award_id AND records.user_id = {$userId}");
$result = array_merge($result, $result0);
// print_r($result);
if($result)
{
echo ajaxResponse(200,$result);
}
else
{
echo ajaxResponse(400);
}
}
Related
Trying to update a record using PHP and PDO statements.
The query fires with no errors, and the console reads the update was successful, but there is no change in the table.
So confused as to why this is happening:
<?php
include("../include/sessions.php");
if(isset($_POST['editcriteria']))
{
$value = $_POST['editcriteria'];
$editUID = $value['editUID'];
$editAddDelete = $value['editAddDelete'];
$editeffectiveDate = $value['editeffectiveDate'];
try
{
$update = $conn->prepare("UPDATE primary_vehicle_data SET `add_delete` = :eadddelete,
`effective_date` = :eeffectivedate WHERE `uid` = :euid");
$update->execute([
'eadddelete' => $editAddDelete,
'eeffectivedate' => $editeffectiveDate,
'euid' => $editUID
]);
if($update)
{
echo "Success: Record Updated";
}
else
{
echo "Error: The Vehcile was not updated.";
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
}
?>
I simplified the above code as much as possible. There were several more parameters, but when I removed the parameters and left it with the 3 parameters above, I still get "Success: Record Updated". But the table is literally unaffected.
Why is this happening and how do I fix it?
* UPDATE *
I already confirmed the connection to the database is good. I'm lost.
$update is a PDOStatement object, so when you test
if ($update)
it will always succeed as a PDOStatement object is equivalent to true.
You should be:
checking the result of $update->execute e.g.
if ($update->execute([ /* params */])) {
checking the value in $update->rowCount, which will tell you if any rows were affected by the query.
Good morning,
I had some problems yesterday and got help, unfortunately, my app still not does 100% does what I want it to do, although only a small detail is missing.
Given a scenario where I want to do an SQL injection to drop a database, and when it happens, render a PHP page. Everything works fine until I want the render to happen - even though the injection executes and the DB is dropped when I check it MySQL, still no rendering. The problem is probably due to the incorrect usage of multi_query. More details in comments in the code.
<?php
include("/../../connection.php");
if(isset($_POST["button_one"])){
$username = $_POST['username'];
$password = $_POST['password'];
if($conn->multi_query("SELECT id FROM users WHERE username = '$username' OR password = '$password'")) // IF THE USER HAS A VALID USERNAME OR PASSWORD,
{
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) { // THEN ENABLE BUTTON TWO, WHICH HAS TO BE CLICKED TO DROP THE DATABASE
echo "
<script type=\"text/javascript\">
document.getElementById('button_two').disabled=false;
</script>
";
}
$result->free();
}
} while ($conn->next_result());
}
}
if(isset($_POST["button_two"])){
$username = $_POST['username']; // SQL INJECTION TO DROP THE DB HAPPENS HERE
$password = $_POST['password'];
if($conn->multi_query("SELECT id FROM users WHERE username = '$username' OR password = '$password'")) // SQL INJECTION SUCCEEDED
{
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) {
if ($result = $conn->query("SHOW DATABASES LIKE 'mydatabase'")) { // NO MORE DATABASE LIKE THAT, IT HAS BEEN DROPPED DUE TO THE INJECTION
if($result->num_rows == 0) {
include("another.php"); // THE PROBLEM IS HERE. EVEN THOUGH THE DB IS DROPPED, THIS PAGE IS NOT RENDERING
}
}
}
$result->free();
}
} while ($conn->next_result());
}
}
?>
Any helpful idea would be appreciated!
The code block to include another.php never runs, because the SHOW DATABASES query fails.
I tested your code and added some error reporting:
if ($result = $conn->query("SHOW DATABASES LIKE 'mydatabase'")) {
if($result->num_rows == 0) {
include("another.php");
}
} else {
echo "Error: {$conn->error}\n";
}
I got this:
Error: Commands out of sync; you can't run this command now
You can't run another SQL query while the one you already have executed still has results to fetch. Even though you have used store_result() to fetch the result set, that only fetches the current result set. You used mulit_query() which produces multiple result sets. You have to process all result sets until the end of the next_result() loop before you can start a new query.
Another lesson here is that you should always check for and report errors after you try to query() or multi_query() or prepare() or execute().
Here's an example: You have to wait until after the last result has been processed before you can run another query. This means after the loop on $conn->next_result() is done.
if(isset($_POST["button_two"])){
$username = $_POST['username'];
$password = $_POST['password'];
if($conn->multi_query("SELECT id FROM users WHERE username = '$username' OR password = '$password'"))
{
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) {
// DISPLAY RESULTS FROM QUERY
}
}
$result->free();
} while ($conn->next_result());
// CAN'T START ANOTHER QUERY UNTIL AFTER THE NEXT_RESULT LOOP IS DONE
if ($result = $conn->query("SHOW DATABASES LIKE 'mydatabase'")) {
if($result->num_rows == 0) {
include("another.php");
}
}
}
I’m trying to write a PHP script with MySQLi to query a database.
I’d like it if the user-input could be checked against the database and then return a result from the column ‘conjugation’ if the string in the column ‘root’ of the table ‘normal_verbs’ is in the input.
So if the user input is something like "foobar", and the root-column has "foo", I'd like it to see 'foo' in 'foobar' and return that value of 'conjugation' in that row.
I can’t seem to get the query to work like I want it to. The one I'm using below is basically just a placeholder. I don't entirely understand why it doesn't work.
What I’m trying, is this :
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('localhost','user','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$m= db_query("SELECT `conjugation` from normal_verbs where `root` in (" . $y . ")");
if($m === false) {
// Handle failure - log the error, notify administrator, etc.
} else {
// Fetch all the rows in an array
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
print_r ($rows);
It’s not giving me any errors, so I think it’s connecting to the database.
EDIT2: I was wrong. I was missing something obvious due to misunderstanding MySQLi and have edited the code accordingly. So the above code does work in that it connects to the database and returns a result, but I'm still stumped on a viable SQL statement to do what I want it to do.
Please try this:
SELECT 'conjugation' FROM 'normal_verbs' WHERE " . $y . " LIKE CONCAT('%',root,'%')
It selects all rows where root contains $y anywhere.
In addition, your code is vulnerable to SQL injections. Please look here for more information.
Try this SQL Query Like this
SELECT `conjugation` from normal_verbs where `root` like '%$y%'
I've tried like twenty times and the closest I got was when I put in a variable stored in row 1 of the db and it returned the content the last row in the db. Any clarity would be extremely helpful. Thanks.
// Create connection
$coco = mysqli_connect($server, $user, $pass, $db);
// Check connection
if (!$coco) { die("Connection failed: " . mysqli_connect_error()); }
// Start SQL Query
$grabit = "SELECT title, number FROM the_one WHERE title = 'on' AND (number = 'two' OR number='0')";
$result = mysqli_query($coco, $grabit);
// What I need it to do
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$titleit = $row["title"];
$placeit = $row["number"];
$incoming = 'Help';
if ($titleit[$_REQUEST[$incoming]]){
$message = strip_tags(substr($placeit,0,140));
}
echo $message;
}
} else {
echo "not found";
}
mysqli_close($coco);
Put the input that you want to match into the WHERE clause of the query, rather than selecting everything and then testing it in PHP.
$incoming = mysqli_real_escape_string($coco, $_POST['Help']));
$grabit = "SELECT number FROM the_one WHERE title = '$incoming' AND number IN ('two', '0')";
$result = mysqli_query($coco, $grabit);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['number'];
}
} else {
echo "not found";
}
I think you need to add a break; in that if or I would assume it would go through each row in the database and set message if it matches the conditional. Unless you want the last entry that matches...if not you should debug:
if ($titleit[$_REQUEST[$incoming]]){
// set message
}
and see when it's getting set. That may not be the issue, but it's at least a performance thing and could explain getting the last entry
Have you tried print_r($row) to see the row or adding echos to the if/else to see what path it's taking?
I get null values when I run this code
$dataArray = mysql_query ("SELECT * from _$symbol order by date DESC limit 10;");
while ($ArrayData = mysql_fetch_assoc($dataArray)) {
$dayData [] = $ArrayData;
}
$todaysdate = $dayData[0]['date'];
$volPercentAVG = $dayData[0]['volume'] / $dayData[0]['_50dayVol'];
mysql_query ("update _$symbol set volPercentAvg=$volPercentAVG WHERE date=$todaysdate;");
It does not return anything, I am not sure I am approaching the MDarray correctly? I have triple checked the column names.
Anywhere to do with this would be helpfull
Thanks.
#Fred-ii- YOU DID IT! Can I or you make this an answer so I can vote for it? If I can I dont see how. – illcrx
Posting my comment as the answer in order to close the question.
If your date column contains any spaces or dots etc. then change WHERE date=$todaysdate
to/and quoting it WHERE date='$todaysdate'
For example: 2014-10-06 22:59:52
Would explain why you were not getting results.
However, I'm quite surprised/baffled that MySQL did not throw you a syntax error, bizarro.
Don't have time to read your entire bit right now, but I can give you my test method from our standard mysqli execution set:
print_r($Record);
This will allow you to see the structure and possibly where your error lies.
I'll also give you our framework which can be very useful (which is why we have it! LOL). Example framework (two functions) to make it easier to use mysqli in php with two lines for each query. It also allows for CLI or web output and debugging which will dump the query (so you can run it) and shows a print_r function to show results.:
This goes at the top:
define('DEBUG', false);
define('CLIDISPLAY', false);
if (CLIDISPLAY) {
define('PRE', '');
define('PRE_END', '');
} else {
define('PRE', '<pre>');
define('PRE_END', '</pre>');
}
require_once("/etc/dbconnect.php");
$DBLink = new mysqli($VARDB_server, $VARDB_user, $VARDB_pass, $VARDB_database, $VARDB_port);
if ($DBLink->connect_errno) {
printf(PRE . "Connect failed: %s\n" . PRE_END, $DBLink->connect_error);
exit();
}
Be sure you have a normal php file at /etc/dbconnect.php with your credentials in it (do not put these in a web folder in case php fails one day and exposes your passwords! LOL). Note that this file can then be shared and loaded only once. It should invoke
# Sample execution
$Query = "select * from vicidial_users where user='6666' and active='Y' limit 1";
$Records = GetData($DBLink, $Query);
print_r($Records[0]); // Single record return access via [0] to access a field named "id": $Records[0]['id']
// Multiple record return access via array walking
foreach ($Records as $Record) {
print_r($Record);
}
$Query = "update vicidial_users set active='Y' where user='6666' limit 1";
UpdateData($DBLink, $Query);
Functions (can be loaded from the credentials file or within your working file or put in a "functions.php" file and "require_once('functions.php');".
function GetData($DBLink, $Query) {
if (DEBUG) {
echo PRE . "Query: $Query\n" . PRE_END;
}
if ($Result = $DBLink->query($Query)) {
if (DEBUG) {
printf(PRE . "Affected rows (Non-Select): %d\n" . PRE_END, $DBLink->affected_rows);
}
while ($Record = $Result->fetch_assoc()) {
$ReturnData[] = $Record;
}
return $ReturnData;
} else {
if (DEBUG) {
printf(PRE . "Errormessage: %s\n", $DBLink->error);
printf("Affected rows (Non-Select): %d\n", $DBLink->affected_rows);
echo "No Records Returned\n" . PRE_END;
}
return false;
}
}
function UpdateData($DBLink, $Query) {
if (DEBUG) {
echo PRE . "Query: $Query\n" . PRE_END;
}
if ($Result = $DBLink->query($Query)) {
if (DEBUG) {
printf(PRE . "%s\n", $DBLink->info);
printf("Affected rows (Non-Select): %d\n" . PRE_END, $DBLink->affected_rows);
}
return;
} else {
if (DEBUG) {
printf(PRE . "Errormessage: %s\n", $DBLink->error);
printf("Affected rows (Non-Select): %d\n", $DBLink->affected_rows);
echo "No Records Returned\n" . PRE_END;
}
return;
}
}