php variable not saving output of query - php

I am very new to PHP and have been trying to find out where I am going wrong in the statement below:
if(empty($_POST['datepickere']))
{
$purchaseorderdate = mysql_query("SELECT purchaseorderDMY FROM purchaseorders WHERE Servicetag = '$_POST[stage]'");
}
else
{
$purchaseorderdate = "$_POST[datepickere]";
}
The else statement executes just fine however the if statement does not save the output of the query to "$purchaseorderdate"
Can someone please give me a pointer as to where I am going wrong? Sorry if there is syntax error or something like that.
datepickere = A field in my HTML form.
purchaseorderDMY = The field in the DB where the datepickere is saved
when a new content is added

Start by making a mysqli connection (this is right out the docs):
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Now update your code snippet with more exact copies from the documentation:
if (empty($_POST['datepickere'])) {
$myvar = mysqli_real_escape_string($link, $_POST['stage']);
$result = mysqli_query("SELECT purchaseorderDMY FROM purchaseorders WHERE Servicetag = '$myvar'");
$row = mysqli_fetch_assoc($result);
$purchaseorderdate = $row['purchaseorderDMY'];
} else {
// you don't need to quote a variable to use it
// but it must be quoted starting at PHP4 (a decade ago)
$purchaseorderdate = $_POST['datepickere'];
}

Related

Checking to see if ID is already in database, if it is don't INSERT it again

When I run the page with an empty database, it will insert the data correctly. When I run the page again, it displays there is already an ID in the database, but it inserts it anyway. Not sure how or why but I've tried every combination of booleans inside the if statements and cant get it to chooch correctly.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database:
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Ask the database for some sweet, sweet data:
$stmt1 = "SELECT orderID FROM orders";
$result = $mysqli->query($stmt1);
//flag (we want to believe that there are no similar IDS so lets make it true):
$flag = true;
//while we got some data, display that shit
while ($row = $result->fetch_assoc()) {
//asign data to variable:
$rowOrderID = $row['orderID'];
//Does it match? if it does set the flag to false so it doesnt get inserted.
if ($rowOrderID == $orderID) {
echo "Row ID" . $row["orderID"] . " Passed ID: " . $orderID . "<br>";
echo "This order is already in the database" . "<br>";
$flag = false;
}
}
//hand the flag over to who ever needs it
return flag;
}
.
if (checkOrderID($orderID) == true) {
//some mysql insert logic here
}
Why are you making this complicated. just do something like this:
$con=mysqli_connect("localhost","root","","price");
$check_query = mysqli_query($con,"SELECT * FROM orders WHERE orderID = $orderID");
if (mysqli_num_rows($check_query) == 0) {
//mysql insert logic here
}
(Noted of course you are going to have your connection logic as well)
Note: You are using Mysqli in object oriented manner but in this example i have not used object oriented manner of DB connection. The connection variable $con must be passed to mysqli_query() method.
Also... random side note, but it's generally a good idea to have a password for your root mysql user.
Here better and short, but please try to use DB connection globally not inside your mothod and try to use prepared statements. But except those you can use following code.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database: I suggest use global DB connection
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//gets recodrs based on $orderID passed to this method
$stmt1 = "SELECT * FROM orders where orderID=$orderID"; //Try to use prepared statement
$result = $mysqli->query($stmt1);
//Store number of rows found
$row_count = $result->num_rows;
if($row_count>0){
return true;
}
else{
return false;
}
}

MYSQL assign column name to variable?

I have a database table which has two columns, business and tourist.
I ask a user to select one of them from dropdown list, then use the result in a SELECT statement in MySQL. I assign this column to $cclass, then I make this statement SELECT $cclass FROM flights ....
But it always returns NULL. Why does it return NULL and how do I fix this?
My code:
$check = mysql_query("SELECT $cclass FROM flights WHERE flight_no = '$flightno'");
while ($result = mysql_fetch_assoc($check))
{
$db_seats = $result['$cclass'];
}
you should replace this line:
$db_seats = $result['$cclass'];
with this:
$db_seats = $result[$cclass];
string between 2 single quotes doesn't parsed:
Strings
Have you tried doing the following:
$check = mysql_query("SELECT".$cclass." FROM flights WHERE flight_no = '$flightno'");
First of all, this code has a serious security issue, as it is vulnerable to SQL Injection. You should be using the MySQLi extension instead, and properly filtering your input.
Try something like this:
<?php
/* Create the connection. */
$mysql = new mysqli("localhost", "username", "password", "myDB");
if ($mysql->connect_error)
{
error_log("Connection failed: " . $mysql->connect_error);
die("Connection failed: " . $mysql->connect_error);
}
/* Sanitize user input. */
if (!in_array($cclass, array('business', 'tourist')))
{
error_log("Invalid input: Must be 'business' or 'tourist'");
die("Invalid input: Must be 'business' or 'tourist'");
}
$statement = $mysql->stmt_init();
$statement->prepare("SELECT $cclass FROM flights WHERE flight_no = ?");
$statement->bind_param("s", $flightno);
if (!$statement->execute())
{
error_log("Query failed: " . $statement->error);
die("Query failed: " . $statement->error);
}
if ($statement->num_rows < 1)
{
echo "No results found.";
}
else
{
$statement->bind_result($seats);
while ($statement->fetch())
{
echo "Result: $seats";
// Continue to process the data... You can just use $seats.
}
}
$mysql->close();
However, the reason your original example is failing, is that you're quoting $cclass:
$db_seats = $result[$cclass];
However, please do not ignore the serious security risks noted above.

Define constant PHP

I have a multi-language script that works like this:
en.php
define('lang_hello_world', 'Hello World!');
index.php
<?php include('en.php'); echo lang_hello_world; ?>
The script works fine and replace the language. But now I need to convert the constant that are stored on MySQL.
The lang_hello_world is in MySQL and I need to print converted on the page, how can I do this?
In the en.php, you need connect the database and define the value, something like this:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = mysqli->query("SELECT * FROM language_table WHERE language = 'EN' LIMIT 1");
$row = $result->fetch_assoc();
define('lang_hello_world', $row[0]['lang_hello_world']);
Hope can help!
Use constant(). If $row['var'] fetched from the database equals lang_hello_world then:
$val = constant($row['var']);
Now $val equals Hello World! if the English file is loaded. Or obviously:
echo constant($row['var']);
Just grab it out of your database before you put it in your constant?
<?php
mysql_connect("localhost", "root", "passw");
mysql_select_db("languages");
$query = mysql_query("SELECT lang_hello_world FROM languages");
$fetch = mysql_fetch_assoc($query);
define("lang_hello_world", $fetch['lang_hello_world']);
mysql_close();
?>

PHP newbie with a perplexing piece of code

this ought to be simple, but it doesn't seem to be working for me. i have tested it with good and bad passwords. no matter what, it will not go into the else statement. i am not sure what i am missing
my code:
$mysqli = mysqli_connect("localhost", "joeuser", "somepass", "testDB");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$sql = "SELECT * FROM login_info";
$res = mysqli_query($mysqli, $sql);
if ($res) {
while ($newArray = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$id = $newArray['first_name'];
$testField = $newArray['last_name'];
echo "The ID is ".$id." and the text is ".$testField."<br/>";
}
} else {
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
}
mysqli_free_result($res);
mysqli_close($mysqli);
}
If i send it a user and password that do exist it does the if statement fine, but if i send it a test for one that is not in the db it still won't do the else? why?
For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a MySQLi_Result object.
A query is only not successful if some serious error occurred. Simply because a SELECT query didn't match any rows doesn't make the query unsuccessful. You'll still get a MySQLi_Result object back. You'll want to check with mysqli_num_rows whether the result set contains any rows.
BTW, save yourself some nesting:
if (!$something) {
exit;
}
// continue as usual
No need for an else here, since you're exiting anyway. Makes things simpler.
Like this:
if ($res) {
while ($newArray = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$id = $newArray['first_name'];
$testField = $newArray['last_name'];
echo "The ID is ".$id." and the text is ".$testField."<br/>";
}
}
if (!isset($id)) {
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
}

Variable scope in PHP

I have an issue with php. The following code generates the error "PHP Warning: mysqli_close() expects parameter 1 to be mysqli, null given[...]" on the line containing the mysqli_query
<html>
<head>
<?php
$table = "prjsuggestions";
/$mysqli = NULL;
if(!empty($_POST['posttext'])){
$pnameempty = empty($_POST['postname']);
$ynameempty = empty($_POST['name']);
if($pnameempty || $ynameempty){
}
else{
$mysqli = new mysqli("localhost", "progclub", "", "progclub");
if(mysqli_connect_errno()){
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//successful query normally occurs here but code fails w/ or /wo it.
}
}
else{
printf("No information posted.");
}
?>
<title>Bucknell Programming Club</title>
</head>
<body>
<span id="posts">
<?php
$offset = 0;
$query = "SELECT * FROM {$table}";
$result = mysqli_query($mysqli, $query);
if($result !== FALSE){
//while(($post = mysqli_fetch_assoc($result)) !== NULL){
echo mysqli_num_rows($result);
$post = mysqli_fetch_assoc($result);
$author = $post['name'];
printf("Author: %s\n", $author);
echo "<br />";
printf("Post title: %s\n", $post['title']);
echo "<br />";
printf("%s\n", $post['text']);
echo "<hr />";
//}
}
else printf("oh nooo!");
mysqli_free_result($result);
mysqli_close($mysqli);
?>
</span>
</body>
</html>
Note that all queries have been checked out and are working correctly in phpmy, and that the original code contains an earlier query that adds data to the 'base, which also definitely works.
I have tried various combinations of static and global, and I have taken a thoroughish look at PHP's page on variable scope, alas I do not entirely understand it in this context (esp. given my inability to make my code work). Can somebody enlighten me as to the differing scopes here? I didn't think there should be any!!
Take a look at the documentation (specifically Example 1). There are a few example similar to yours.
The following should work, and it is similar to your code:
Note how the first argument of mysqli_query() is in fact your variable $mysqli. You were probably trying to put something else there.
Also, be sure to check your connection, like in the code below:
<html>
<head>
<?php
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
?>
</head>
<body>
<?php
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Use $mysqli */
if (mysqli_query($mysqli, "/* ... MySQL goes here... */") === TRUE) {
/* Success! */
}
mysqli_close($mysqli);
?>
</body>
</html>
OOOOOOOOOOoooooooooooooooooohh. D'oh. Yeah. Scope. Perhaps I should have though more about the fact that the variable is only initialized when data is written. Oops. Thanks guys.

Categories