I think I didn't understand the PHP logic yet. My "if's" in javascript works fine, but in PHP it's always ignored. I have this form (party of it) in insert_car.php:
<input type="file" name="imagem01" id="imagem01" title="Imagem 01" onchange="readURL01(this);" class="button" />
... (and 5 more inputs for images and others for texts)
this is the correspondent party in insert_db.php:
$gravar_imagem01 = $_FILES['imagem01'];
preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $gravar_imagem01["name"], $ext);
$nome_imagem01 = md5(uniqid(time())) . "." . $ext[1];
$caminho_imagem01 = "../../images/" . $nome_imagem01;
move_uploaded_file($gravar_imagem01["tmp_name"], $caminho_imagem01);
$sqlinsert = "INSERT INTO tb_carros (... imagem01,...) value (... '$nome_imagem01',...)";
It works fine, but know I want to put an default image if one of the inputs file is empty. So I did this in insert_db.php:
if (empty($imagem01))
{
$gravar_imagem01 = "sem_imagem.jpg";
$nome_imagem01 = $gravar_imagem01;
}
else
{
$gravar_imagem01 = $_FILES['imagem01'];
preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $gravar_imagem01["name"], $ext);
$nome_imagem01 = md5(uniqid(time())) . "." . $ext[1];
$caminho_imagem01 = "../../images/" . $nome_imagem01;
move_uploaded_file($gravar_imagem01["tmp_name"], $caminho_imagem01);
}
The default image (sem_imagem.jpg) is been placed, but even if the input "imagem01" is not empty the default image appears. So, what is wrong in my code?
Ps.: If I switch the "if" and "else" condition the result is the reverse (the default image don't appears even with the input imagem01 empty). That's why I said that my "if" is been ignored.
Try this with isset
change this
if (empty($imagem01))
to
$gravar_imagem01 = $_FILES['imagem01'];
if (isset($gravar_imagem01))
The if isn't being "ignored"; you likely misunderstood the meaning of the function empty. Look it up in the documentation, and check that it does what you think it does.
In particular, it doesn't magically understand the concept of "files" — empty looks at variables. It is quite conceivable that $_FILES['imagem01'] still exists in some form even in the case in which you're perceiving the image file to be "empty". I suggest examining it in this case to find out which conditional to use.
Edit: It also helps if you use the correct variable name:
if (empty($imagem01))
becomes:
if (empty($_FILES['imagem01']))
try this i think always $imagem01 is empty you must get imagem01 data from form like $imagem01= $_FILES['imagem01']; then check for empty you can't use JavaScript variable directly it better in this case use var_dump($var); for see variable value
$imagem01= $_FILES['imagem01'];
if (empty($imagem01))
{
$gravar_imagem01 = "sem_imagem.jpg";
$nome_imagem01 = $gravar_imagem01;
}
else
{
$gravar_imagem01 = $_FILES['imagem01'];
preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $gravar_imagem01["name"], $ext);
$nome_imagem01 = md5(uniqid(time())) . "." . $ext[1];
$caminho_imagem01 = "../../images/" . $nome_imagem01;
move_uploaded_file($gravar_imagem01["tmp_name"], $caminho_imagem01);
}
There is no variable named $imagem01 anywhere else in your code so it is always going to be undefined and empty($imagem01) will always return true. You may need to check for a different condition in your if statement.
Related
I am writing some code to create fields automatically, which will save me a load of time. I have got most of my code working, but I have came across one error with the code, which is preventing me from achieving my final goal.
The code is as follows:
while ($i <= $numFields) {
$type = "\$field{$i}_Data['type']";
$name = "\$field{$i}_Data['name']";
$placeholder = "\$field{$i}_Data['placeholder']";
$value = "\$field{$i}_Data['value']";
echo '<input type="'.$type.'" name="'.$name.'" placeholder="'.$placeholder.'" value="'.$value.'">';
$i++;
}
The $numFields variable is defined at the top of my script, and I have worked out that it is something to do with how I am setting the variables $type, $name etc.
The end result is to create inputs depending on properties set in variables at the top of the script, The only issue I am having is with the settings of the variables, as said above.
If any extra code/information is needed, feel free to ask.
Thank you.
NOTE - There is no physical PHP error, it's purely an error with this:
"\$field{$i}_Data['value']";
There are a few ways we could write this one out, but they are all extensions of variable expansion and/or variable-variables.
Basically, we just need to put the variable name in a string and then use that string as the variable (much like you're currently doing with $i inside the string):
$type = ${"field{$i}_Data"}['type'];
$name = ${"field{$i}_Data"}['name'];
// ...
However, if you don't mind an extra variable, this can be written more cleanly by saving it like so:
$data = ${"field{$i}_Data"};
$type = $data['type'];
$name = $data['name'];
// ...
There are two columns in the database table "system". I have the systemId and want to get the mobileSystemId. But the variable $mobileSystemIds which I already defined as global is always empty.
EDIT: Now array_map doesn´t work. I always get my Exception output "Arrayfehler ArrayMap"
I have the following code :
$mobileSystemIds=array();
function getMobileSystemId($systemId)
{
global $mysqli;
global $mobileSystemIds;
$query="SELECT mobileSystemId FROM system WHERE systemId ='" .$systemId ."'";
if(!$result=$mysqli->query($query))
{
echo "Datenbankfehler DB-QUery";
exit(0);
}
if (!$mobileSystemId=$result->fetch_assoc())
{
echo "Datenbankfehler DB-Fetch";
exit(0);
}
$mobileSystemId=$mobileSystemId["mobileSystemId"];
echo "mobile System ID: " .$mobileSystemId ."<br />";
return $mobileSystemId;
}
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
In this case, using a return in your function would be much cleaner.
Nothing to do with your problem, but is your $systemId var trusted ? (To prevent SQL injection).
Update:
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
ought to read (just checked; it works for me):
$mobileSystemIds = array_map('getMobileSystemId', $systemsList);
if (empty($mobileSystemIds))
{
if (empty($systemsList) || !(is_array($systemsList)))
echo "OK: no mobile IDs, but no systems either";
else
echo "THIS now is strange :-(";
}
else
{
echo "Alles OK";
var_dump($mobileSystemIds);
}
I tried this by returning a dummy value based on input; if it does not work for you, there must be something strange in the database.
(Update: the text below refers to your original code, which did not use array mapping)
Your code ought to be working as it is. You put several $mobileSystemId 's into a single $mobileSystemId.
It works: I tested with a simpler code, removing the DB calls but leaving your code, and spelling, untouched.
So, the error must be elsewhere. I would guess that this code is included into something else, and:
the $mobileSystemIds = array(); declaration gets executed more than once, thereby losing all its data;
the $mobileSystemIds = array(); declaration is itself included in a more local scope and you read it from outside, reading an empty value or a totally different value.
Try replacing the first part of your code with:
GLOBAL $mobileSystemsIds;
if (defined($mobileSystemsIds))
trigger_error("mobileSystemsId defined more than once", E_USER_ERROR);
else
$mobileSystemsIds = array();
and also, in the function body:
if (!defined($mobileSystemsId))
trigger_error("mobileSystemsId should have been defined", E_USER_ERROR);
I have an input box that with php will echo out names typed in. The problem is that when the user presses space it will echo out the blank character. I have searched and didnt find an absolute answer. I know that using !empty if there is absoutely anthing in the input field but if there is a space is null supposed to work.
How to avoid getting echo if there is blank space in input?
if (!empty($name['name']) || null ) {
echo 'Your name is '.$name;
}
{
//do nothing
}
Calls to the function empty() will be true if it is unset, null, empty string, boolean false, or 0. Still I like avoiding heavy logic in conditionals... pull out the trimming and prepping the string before testing.
$nameString = empty($name['name'])?null:trim($name['name']);
if(!empty($nameString){
//go to town here
}
To appease the fanatics in advance, I have to also add that you should escape any user input before printing it. That way you protect against XSS. To be safer add try this:
$nameString = empty($name['name'])?null:trim($name['name']);
$nameString = htmlentities($nameString, ENT_QUOTES);
if(!empty($nameString){
//go to town here
}
However, a side note... the htmlentities() call does not protect against SQL injection, so if this data is going into a db you'll have to do more work--since your question doesn't indicate you're doing anything else than printing out to screen, we can hold off the SQL injection discussion for another day.
You want to check if there is a space, you may want to do this:
if ($name['name'] != null && trim($name['name']) != "" && !strpos(trim($name['name']), " "))
{
// work with $name['name']
}
else
{
// nothing
}
Be careful using empty(), it will return TRUE if the user enters '0'.
You might want to use strlen()
I've started using PHP lately... all is good except one thing.
I am trying to call a function from another php file... but it's not working.
It's probably really simple, but I haven't found anything useful to solve it.
I've used "required_once " but it still does not work.
Does anyone know where I'm going wrong?
<?php
require_once "/Applications/MAMP/htdocs/me/database_functions.php";
require_once "/Applications/MAMP/htdocs/me/encode_decode.php";
if (isset($_POST['url']) && $_POST['url'] != "http://")
{
//Get the url posted
$long_url = $_POST['url'];
//Create record in long_url table and return it's id
$long_id = create_long_url($long_url);
Everything works so far.. But
the problem is this next function call.. it doesn't even go into the function.
$short_url = $encode($long_id);
}...............etc...
encode_decode.php looks a bit like this...
<?php //encode_decode.php
function encode($number)
{
echo "<br />in encode";
//Encode numer to 6 char
$s = strtr(rtrim(base64_encode(pack('i', $number)), '='), '+/', '-_');
echo $s;
return $s;
}
Any help is greatly appreciated...
You don't need the $ before your function call
$short_url = $encode($long_id);
should be
$short_url = encode($long_id);
The dollar sign would only be needed if the function is stored in a variable (which it isn't).
$short_url = encode($long_id);
remove the dollar sign from in front of the function. a dollar sign in PHP indicates a variable
As all others have said:
$short_url = encode($long_id);
But also you could clean up your require_once statements:
define('DS', DIRECTORY_SEPARATOR);
require_once(dirname(__FILE__) . DS . 'database_functions.php');
require_once(dirname(__FILE__) . DS . 'encode_decode.php');
Instead of the define() and reference to DS you could of course just prefix your file names with '/'. This also assumes your files are relative (but if not just prefix the folder to the filename) - this would make sure you don't get any problems if you move your site from different servers (i.e., testing, production).
I am writing a php function for wordpress that is executed through an XML feed. Therefore we are excepting a feed and then based on the nodes placing those in our website. What I need help with is we have a bunch of different images of credentials (i.e BBB, chamber of commerce etc) What I need therefore is when there is a link to a BBB then it should display a picture, if not then it should be blank. The problem I am running into is because the BBB links will be random based on different businesses. Any help would be greatly appreciated. Thanks.
If URL "pic"
else "no pic"
Do you mean this? Otherwise please explain your problem better.
if (!empty($url)) {
echo '<img src="' .$url. '" />';
}
else {
echo ' ';
}
Check here when empty returns false (and therefore !empty is true) and really consider if this fits your needs.
Maybe I'm missing something, but wouldn't this do?
if($license1) { print "<img src=\"/path/to/bbb.logo\" alt=\"BBB Logo\" />"; }
A method would be creating an array
like $feeds = array("pic","xml");
then testing if its in array like
if in_array($url,$feeds)
// your code;
or the second method would be creating an temp var like $tmp = $url =="pic" ? "pic" : "nopic";
or to set just an boolean $tmp = $url =="pic" ? TRUE : FALSE;
then you can test it like this
if($url) // if its == "pic" it would return true otherwise false
//make your url
Also a shorthand way is to do
But when the given var is an array I think you need to use is_array(), or if it's a class objec,t use is_object() to verify that it has content.